How to add users from .csv by specific field?

Solution 1:

Carrying over from my previous answer in your other question How to grab characters before comma in a list and export to a script? , use awk with $FIELD == "word". Here male and female are set in field 5

awk -F',' '$5=="male" {command=sprintf("useradd \"%s\" ",$1); system(command) }' input.txt

You can do same for "female"

Solution 2:

You could try

sudo awk -F , '($5=="male") {system("useradd " $1)}' file.csv

Solution 3:

If you want to search for a pattern and fields may be inconsistent (ie if gender might not always be in the 5th field), you could use a sed way to grab the first field if female is in any field, for example:

sed -nr 's/^([^,]+),.*,female,.*/\1/p' file

Explanation

  • -n don't print until we ask for something
  • -r use ERE
  • s/old/new replace old with new
  • ^([^,]+), save some characters before a comma at the start of each line (the first field)
  • ,.*, any number of any characters that might occur between two commas (so it doesn't matter how many fields there are between the first field and the pattern)
  • ,female, the line will only match if this pattern occurs
  • \1 the saved pattern in () from earlier
  • p print only the lines that we changed