[author's note: personally, I use awk a bunch in MySQL DBA work, for tasks like scrubbing data from a production export for use in qa/dev, but usually have to resort to Perl for really complex stuff, but now I know how to do .]
Basics:
By default, fields are separated by any number of spaces. The -F
option to awk changes the separator on commandline.
Print the first field, fields are separated by a colon.
awk -F: '{print $1}' /etc/passwd
Print the first and fifth field:
awk -F: '{$print $1,$5}' /etc/passwd
Can pattern match and use files, so you can replace:
grep foo /etc/passwd | awk -F: '{print $1,$5}'
with:
awk -F: '/foo/ {print $1,$5}' /etc/passwd
NF = built in variable (no $) used to mean “field number”
This will print the first and last fields of lines where the
first …