Reputation: 13
I used the awk
command to get the list of users from /etc/passwd. Now I want to number it, this is the command I used but it doesn't seem to work, how do I get it to work?
s=0
awk -F':' '{s+=1} END {print "USER"$s" = " $1}' /etc/passwd
I expect it to output:
USER1 = xyz
USER2 = abc
And so on
Upvotes: 0
Views: 195
Reputation: 17028
The reason why you only get one result line is that your print matches only one single line (the last) because you use the END
keyword.
You don't need to set s=0
in your shell as variables are handled by awk itself. And as @JonathanLeffler mentions, $
selects a field in awk. So $s
will not be replaced by the value of variable s
, but by the field s
, where s
is the variable value. (if s == 2
, you'd print field number 2.)
Try this:
# Start with 0 (using an extra variable s)
awk -F':' '{print "USER"s++" = " $1}' /etc/passwd
# Start with 1 (using the internal variable NR)
awk -F':' '{print "USER"NR" = " $1}' /etc/passwd
# Produce sortable output for further processing
awk -F':' '{printf "USER%04d=%s\n", NR-1, $1}' /etc/passwd
Thanks to the commenters for more ideas.
Upvotes: 3