Search code examples
unixcommand-lineawkcentosifs

Extract info from a text file and use it in a command in unix


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.


Solution

  • 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.