2

I have a file containing a list of users and information, each line is a separate user written like so:

alfred,butler,male,70,7:15. 

I want to grab the names only from the list so I can create a user for them.

Once I have the names I can simply use a for loop and echo useradd with each of the usernames then simply copy and paste the text. How do I approach grabbing the characters before the first comma?

Zanna
  • 72,312
Danny
  • 95

2 Answers2

3

You could use cut to grab the first field and then pipe into a while loop to run commands with the names as input:

cut -d ',' -f1 file | while read line; do echo "$line"; done

obviously this script is not doing anything useful as it is - replace echo with whatever you want to do to each name, for example sudo useradd (after testing with echo)

Explanation

  • -d ',' use comma as delimiter (d)
  • -f1 the first (1) field (f)
  • while read line reading from the file, loop over each line as variable $line
  • do <command> "$line" execute <command> on the argument expanded from the variable (ie on each line of the piped output)
Zanna
  • 72,312
2

Extracting the names is easy: use awk with -F flag to print first field

awk  -F, '{print $1}' input.csv

In order to actually add users, you need to read output of awk , line by line. One way to do so is how Zanna shows, with pipe to while read variable ; do . . . done.

Alternative would be to take advantage of awk's system() function to create command first and pass it to the function. Consider this:

$ awk -F ',' '{command=sprintf("useradd \"%s\"",$1);print command  }' input.txt                                          
useradd "alfred"
useradd "johnny"

For each line we extract first word and put it into useradd "%s". That can be given to system() function and it will run with /bin/sh

Running this as root:

$ awk -F ',' '{command=sprintf("useradd \"%s\" ",$1); system(command) }' input.txt
$ grep 'alfred' /etc/passwd
alfred:x:1001:1001::/home/alfred:

CAUTION: system() calls /bin/sh , which on Ubuntu is symlink to /bin/dash. Therefore avoid bashisms in the command you pass