Reputation: 37
I have a file with a wrong structure, which I convert to the correct structure using a while..read loop
userid1:john doe smith:group1
userid2:jane doe smith:group2
userid3:paul rudd :group2
Code so far:
while IFS=: read userid username; do
userid=`echo $username|cut -d ":" -f 1`
echo "$userid:password:$username:/home/$userid/bin/bash";
done < users.txt > newusers.txt
Which gives me this output,
userid1:password123:John Doe Smith:/home/userid1/bin/bash
userid2:password123:Jane Doe Smith:/home/userid2/bin/bash
userid3:password123:Paul Rudd:/home/userid3/bin/bash
Now I need to append the uid (auto-generate, so blank) and the gid, not sure how to do so, I already have the groups created with 2020 and 2040.
Desired output:
userid1:password123::2020:John Doe Smith:/home/userid1/bin/bash
userid2:password123::2040:Jane Doe Smith:/home/userid2/bin/bash
userid3:password123::2040:Paul Rudd:/home/userid3/bin/bash
Cheers.
Upvotes: 0
Views: 54
Reputation: 203324
$ cat tst.awk
BEGIN {
FS = "[[:space:]]*:[[:space:]]*"
OFS = ":"
gid["group1"] = 2020
gid["group2"] = 2040
}
{ print $1, "password123", "", gid[$3], $2, "/home/" $1 "/bin/bash" }
$ awk -f tst.awk file
userid1:password123::2020:john doe smith:/home/userid1/bin/bash
userid2:password123::2040:jane doe smith:/home/userid2/bin/bash
userid3:password123::2040:paul rudd:/home/userid3/bin/bash
Note that the above removes the undesirable blank after paul rudd
from your input. Now to also convert the first the letter in each name to upper case would be:
$ cat tst.awk
BEGIN {
FS = "[[:space:]]*:[[:space:]]*"
OFS = ":"
gid["group1"] = 2020
gid["group2"] = 2040
}
{
name = ""
numParts = split($2,parts," ")
for (i=1; i<=numParts; i++) {
part = parts[i]
name = (i>1 ? name " " : "") toupper(substr(part,1,1)) substr(part,2)
}
print $1, "password123", "", gid[$3], name, "/home/" $1 "/bin/bash"
}
$ awk -f tst.awk file
userid1:password123::2020:John Doe Smith:/home/userid1/bin/bash
userid2:password123::2040:Jane Doe Smith:/home/userid2/bin/bash
userid3:password123::2040:Paul Rudd:/home/userid3/bin/bash
Upvotes: 0
Reputation: 140277
awk
can do it all
$ awk -F: '{gid=$3=="group1" ? "2020":"2040";print $1 FS "password123" FS FS gid \
FS $2 FS "/home/" $1 "/bin/bash" }' ./users.txt
userid1:password123::2020:john doe smith:/home/userid1/bin/bash
userid2:password123::2040:jane doe smith:/home/userid2/bin/bash
userid3:password123::2040:paul rudd:/home/userid3/bin/bash
Upvotes: 0
Reputation: 140960
I think your code could look like:
while IFS=: read -r userid username group; do
if [ "$group" = "group1" ]; then
groupid=2020
elif [ "$group" = "group2" ]; then
groupid=2040
else
echo "Unknown groupid"
do something with error.
fi
echo "$userid:password123::$groupid:$username:/home/$userid/bin/bash";
done < users.txt > newusers.txt
Upvotes: 1