[ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Many useful awk
programs are short, just a line or two. Here is a
collection of useful, short programs to get you started. Some of these
programs contain constructs that haven't been covered yet. The description
of the program will give you a good idea of what is going on, but please
read the rest of the Info file to become an awk
expert!
Most of the examples use a data file named `data'. This is just a placeholder; if you were to use these programs yourself, you would substitute your own file names for `data'.
Since you are reading this in Info, each line of the example code is enclosed in quotes, to represent text that you would type literally. The examples themselves represent shell commands that use single quotes to keep the shell from interpreting the contents of the program. When reading the examples, focus on the text between the open and close quotes.
awk '{ if (length($0) > max) max = length($0) }
END { print max }' data
awk 'length($0) > 80' data
expand data | awk '{ if (x < length()) x = length() }
END { print "maximum line length is " x }'
expand
program to change tabs into spaces,
so the widths compared are actually the right-margin columns.
awk 'NF > 0' data
awk 'BEGIN { for (i = 1; i <= 7; i++)
print int(101 * rand()) }'
ls -lg files | awk '{ x += $5 } ; END { print "total bytes: " x }'
ls -lg files | awk '{ x += $5 }
END { print "total K-bytes: " (x + 1023)/1024 }'
awk -F: '{ print $1 }' /etc/passwd | sort
awk 'END { print NR }' data
awk 'NR % 2 == 0' data
[ << ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |