Ubuntu – How to add users from .csv by specific field

command linecsvtext processing

I'm trying to sort my users into specific servers, so what I'm trying to do at the moment is grab all the users by gender. Essentially I would have one server with all male users and one with all female users. The data in the file per line is read as so:

jimlee,7676,jim lee,sony,male,8912,1543,33:44

The command I'm using below grabs the first field and then adds the user. However my goal is to add a specific gender only and create a user for them. So seeing how the fifth field is the gender field I know that using -f5 will give me that field and would display all the users by gender but I'm not sure how to grab the name based on a specific field, in this case the fifth field (gender).

cut -d ',' -f1 file.csv | while read line; do sudo useradd "$line"; done

Best Answer

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"