Hébergement
Forum
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 book 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'.
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' data