1832935 Members
2939 Online
110048 Solutions
New Discussion

awk help

 
Hanry Zhou
Super Advisor

awk help

for i in `cat /tmp/users.dat`
do
USER=`echo $i | awk -F":" '{print $1}'`
UID=`echo $i | awk -F":" '{print $2}'`
GROUP=`echo $i | awk -F":" '{print $3}'`
DIR=`echo $i | awk -F":" '{print $4}'`
SHELL=`echo $i | awk -F":" '{print $5}'`
COMMENTS=`echo $i | awk -F":" '{print $6}'`
done


The sample of the line in t/mp/users.dat is following:
user:uid:group:dir:shell:firstname lastname,location,phone,

My question is: how can I assign the rest portion of the line
after"shell:" to $6?
The current script only assign "firstname" to $6, and it cuts off the portion of
" lastname,location,phone,".

Thanks,
none
9 REPLIES 9
curt larson_1
Honored Contributor

Re: awk help

just testing
no points
curt larson_1
Honored Contributor

Re: awk help

an different way would be

oldIFS="$IFS"
IFS=":"

cat /tmp/users.dat |
while read USER UID GROUP DIR SHELL REST
do
print $USER
print $REST
#etc
done
IFS="$oldIFS"

sorry for the test, but I hadn't been able to reply for a month or so
curt larson_1
Honored Contributor

Re: awk help

another way

only works if ":" is only used as field seperator

cat tmp/users.dat | tr ":" " " |
read USER UID GROUP DIR SHELL COMMENTS
print $USER
print "$COMMENTS"

if there are extra fields read will place them all in the last variable name
curt larson_1
Honored Contributor

Re: awk help

oops really should be a while loop in that last suggestion:

cat tmp/users.dat | tr ":" " " |
while read USER UID GROUP DIR SHELL COMMENTS
do
print $USER
print "$COMMENTS"
# etc
done
A. Clay Stephenson
Acclaimed Contributor

Re: awk help

Here is one approach:
#!/usr/bin/sh
FNAME=/tmp/users.dat
cat ${FNAME} | while read i
do
USER=$(echo ${i} | awk -F":" '{print $1}')
UID=$(echo ${i} | awk -F":" '{print $2}')
GROUP=$(echo ${i} | awk -F":" '{print $3}')
DIR=$(echo ${i} | awk -F":" '{print $4}')
SHELL=$(echo ${i} | awk -F":" '{print $5}')
COMMENTS=$(echo ${i} | awk -F":" '{print $6}')
done
If it ain't broke, I can fix that.
curt larson_1
Honored Contributor

Re: awk help

could always do it this way

COMMENTS=`echo $i | cut -d":" -f6
curt larson_1
Honored Contributor

Re: awk help

or as

cat /tmp/users.dat |
while read line
do
comment=${line##*:}
done
Hanry Zhou
Super Advisor

Re: awk help

Curt,

Thanks for your messages,

Could you please explore this a little bit more:
comment=${line##*:}

Points will be followed.
none
Vitek Pepas
Valued Contributor

Re: awk help

It means 'comment equals everything after the last colon in the line'