To assign variable from a file separated by delimiter
5,741
Solution 1
If you don't want to use awk
you can do something like
while IFS=: read -r uid username userid; do
printf "user:%s\nusername:%s\nuserid:%s\n" "$uid" "$username" "$userid";
done <file
user:1000
username:Tom
userid:user1
user:1002
username:Jerry
userid:user2
user:1003
username:Victor
userid:user3
user:1004
username:Jason
userid:user4
IFS
is the input record separator, by setting it to :
you can read the variables from the file directly.
Solution 2
See the below awk script:
user@host:~# awk -F: '{printf "uid:%s\nusername:%s\nuserid:%s\n", $1,$2,$3}' file
uid:1000
username:Tom
userid:user1
uid:1002
username:Jerry
userid:user2
uid:1003
username:Victor
userid:user3
uid:1004
username:Jason
userid:user4
Solution 3
for i in `cat text_file`;do uid=`echo "$i"|cut -d: -f1`; username=`echo "$i"|cut -d: -f2`; userid=`echo "$i"|cut -d: -f3`; echo "uid=$uid,username=$username,userid=$userid";done
uid=1000,username=Tom,userid=user1
uid=1002,username=Jerry,userid=user2
uid=1003,username=Victor,userid=user3
uid=1004,username=Jason,userid=user4
So you have variables $uid
, $username
, $userid
to use.
Is that good?
Related videos on Youtube
Author by
Venom
Updated on September 18, 2022Comments
-
Venom over 1 year
I have a text file with datas as below separated by delimiter:
1000:Tom:user1 1002:Jerry:user2 1003:Victor:user3 1004:Jason:user4
I need to run a while loop (any loop) to fetch details from first line and assign variable as below:
uid:1000 username:Tom userid:user1
This script should be able to collect details till the end of file "data". I can do this part once I am able to do for the first line.