简体   繁体   中英

reading from 2 files in a while loop BASH SCRIPTING

I have 2 files one named Group.csv Containing

thisisgroupone

and another named Users.csv

Testuser1,Testuser2,TestUser3

This my script so far:

# this part of the script will now add the created users into the created group!
while IFS=, read col1 col2 col3
do
        usermod  -g $READ GROUP.CSV$ $col1
        usermod  -g $READ GROUP.CSV$ $col2
        usermod  -g $READ GROUP.CSV$ $col3

    done < Users.csv

echo "Users now moved to new group sepcifyed in Group.csv"
  • Im trying to figure out a way to read both files at once to complete this statement.

Thanks =D

One technique is:

while IFS=, read col1 col2 col3
do
        read -u 3 GROUP
        usermod  -g $GROUP $col1
        usermod  -g $GROUP $col2
        usermod  -g $GROUP $col3
done < Users.csv 3< Group.csv

or

while IFS=, read col1 col2 col3 && read -u 3 GROUP
do
        usermod  -g $GROUP $col1
        usermod  -g $GROUP $col2
        usermod  -g $GROUP $col3 
done < Users.csv 3< Group.csv

Neither of the above ensures that the files have the same number of lines, and you might want to check that.

paste -d' ' Group.csv Users.csv will generate output such as:

Testgroup1 Testuser1 Testuser2 Testuser3
Testgroup2 Testuser4 Testuser5 Testuser6
...

so you can send the output of this to your script and it can read lines from a single file in which the first field of each line is the group and the remaining are users.

You can either use | to send the output of paste directly to your script. Or you can create a temporary file paste -d' ' Group.csv Users.csv > temp.csv and then use < temp.csv to read the file.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM