Awk: Difference between revisions
Appearance
No edit summary |
No edit summary |
||
Line 58: | Line 58: | ||
then use awk like this: | then use awk like this: | ||
$ awk -f maxuid /etc/passwd | $ awk -f maxuid /etc/passwd | ||
to ignore user nobody: | |||
<pre>BEGIN {maxuid = 0; FS=":" } | |||
$1 != "nobody" { if ($3 > maxuid) maxuid = $3 } | |||
END { print" the largest UID is ", maxuid } | |||
</pre> |
Revision as of 16:15, 9 October 2014
awk
pattern {action} pattern {action}
$ awk '{print $2}' /etc/fstab
to filter out comment lines - starting with #
$ awk '/^[^#]/ {print $2}' /etc/fstab
print first field from password file using field seperator ':'
$ awk -F: '{print$1}' /etc/passwd
print only user ID > 500
$ awk -F: '$3>=500 {print$1}' /etc/passwd
display average of numbers entereed on a line:
$ awk '{ sum=0; for (i=1; i<=NF; i++) sum +=$i; print sum/NF; }'
NF | number of fields in the current line |
NR | the current record number (line number) |
FS | input field seperator (space by default) |
RS | record seperator (newline by default) |
Example | Example |
Example | Example |
Example | Example |
Example | Example |
Example | Example |
show the 5th record on the second line:
df /tmp | awk 'NR==2 {print$5 }'
use awk with a program
the file maxuid:
BEGIN {maxuid = 0; FS=":" } { if ($3 > maxuid) maxuid = $3 } END { print" the largest UID is ", maxuid }
then use awk like this:
$ awk -f maxuid /etc/passwd
to ignore user nobody:
BEGIN {maxuid = 0; FS=":" } $1 != "nobody" { if ($3 > maxuid) maxuid = $3 } END { print" the largest UID is ", maxuid }