1833870 Members
1582 Online
110063 Solutions
New Discussion

awk command question

 
SOLVED
Go to solution
MikeL_4
Super Advisor

awk command question


I am creating a file if userid and uid from the passwd file using:

cat /etc/passwd | awk -F":" {print $1 ,$3}

but I also need to insert the hostname into the output, is there a way get this into the awk statement, I already have a variable set for HOST from a command:
HOST=`hostname`
issued earlier in the script.

Thanks
3 REPLIES 3
Dave Olker
Neighborhood Moderator
Solution

Re: awk command question

Hi Mike,

You could try using the -v option for awk to set a variable like "HOST" equal to the local hostname and then print the results like this:

cat /etc/passwd | awk -v HOST=`hostname` -F":" '{print HOST, $1 ,$3}'

On my system this returns:

ros87252 root 0
ros87252 daemon 1
ros87252 bin 2
ros87252 sys 3
ros87252 adm 4
ros87252 uucp 5
ros87252 lp 9
ros87252 nuucp 11
...

Regards,

Dave


I work at HPE
HPE Support Center offers support for your HPE services and products when and how you need it. Get started with HPE Support Center today.
[Any personal opinions expressed are mine, and not official statements on behalf of Hewlett Packard Enterprise]
Accept or Kudo
curt larson_1
Honored Contributor

Re: awk command question

another way using awk:

If you have a recent version of awk, such as on 11i, you can do it this way:

awk -F":" '{
print $1, $3, ENIVRON["HOST"];
}'

I'm not sure if HOST needs to be exported from the environment or not.

or you can just do it in the shell

oldIFS="$IFS"
IFS=":"
while read userid x uid stuff
do
print $userid $uid $HOST
done < /etc/passwd
IFS="$oldIFS"
curt larson_1
Honored Contributor

Re: awk command question

oops that should have been
ENVIRON
and not
ENIVRON