2

I am trying to extract info from a .list file called 'accounts.list' and use the extracted info in a command line operation in CentOS 7. I know there is a simple solution but I cannot for the life of me find it.

So the file has each line listed in the following format:

John Smith | jsmith
Jane Doe | jdoe

What I need to do is add users with the information from each line. So for example I would like to add each part to a variable, and then use the variable in a adduser command:

fn=John
ln=Smith
un=jsmith

useradd -c "$fn $ln" $un

So I need to go through each line and extract that info, add the user, and then continue on to the next line. I want to do this in the simplest way possible, but nothing I've tried has worked, any help would be greatly appreciated.

hazy7687
  • 67
  • 8
  • 1
    Note that shell assignments are not usually prefixed with a `$`; you almost certainly wanted `fn=John`. As written, if `fn=XYZ`, then `$fn=John` sets `$XYZ` to `John`. – Jonathan Leffler Sep 15 '15 at 05:08
  • Thank you Jonathan, yes I was writing it incorrectly, I'm still very new to shell commands (as I'm sure you can tell). – hazy7687 Sep 15 '15 at 05:39

1 Answers1

2
while read -r fn ln ignore un; do useradd -c "$fn $ln" "$un"; done <accounts.list

Or, if you prefer commands spread over multiple lines:

while read -r fn ln ignore un
do
    useradd -c "$fn $ln" "$un"
done <accounts.list

How it works

Each line of your file has four fields: the first name (fn), the last name (ln), the vertical bar, the username (un). The command read reads from the input file line-by-line and assigns these four fields to the variables fn, ln, ignore, and un.

John1024
  • 109,961
  • 14
  • 137
  • 171
  • 1
    Thank you John, you won't believe how similar of a solution I was trying but I was doing a few things wrong. Yours worked like a charm though and was nice and clean :) – hazy7687 Sep 15 '15 at 05:42