Home > OS >  How to assign variable from grep output in a while loop
How to assign variable from grep output in a while loop

Time:10-20

I wanted to create a variable for each grep regex line from Usernames.txt file. The text contains this

mario,visitor
bobmarley,staff
luigi,visitor
hailey,visitor

and so on.

I want the name from before the comma as a username and visitor as the group for the user

#!/bin/bash
sudo addgroup visitor
sudo addgroup staff

filename='Usernames.txt'

while read line; do
username=$(echo $line | grep -o '^[a-z]*[^,]')
group=$(echo $line | grep -o '[^,][a-z]*$')
sudo useradd $username -G $group -p $username
done < $filename

but the output says command username not found. So instead I tried not so efficient method

while read line; do
sudo useradd $(echo $line | grep -o '^[a-z]*[^,]') -G $(echo $line | grep -o '[^,][a-z]*$') -p $(echo $line | grep -o '^[a-z]*[^,]')
done < $filename

I want the result of each loop to be like this

sudo useradd mario -G visitor -p mario

How do I improve this? Thanks!

CodePudding user response:

Try this approach

while read -r name role; do
    sudo useradd $name -G $role -p $name
done < <(sed 's/,/ /' $filename)

Actually sed is enough:

sudo sed 's/\(.*\),\(.*\)/useradd \1 -G \2 -p \1/e' $filename
  • Related