Useful AWK One-Line Commands
AWK is a programming language that includes user-defined functions, multiple input streams, and computed regular expressions. The name AWK comes from the initials of its designers - Alfred V. Aho, Peter J. Weinberger, and Brian W. Kernighan. It is a powerful scripting language included with most implementations of UNIX. Awk supplements the file-processing capabilities of the UNIX shells, including pattern-matching of fields and C-like structured programming constructs. An awk program is a sequence of patterns and corresponding actions that are carried out when a pattern is read. The awk program is a more powerful tool for text manipulation than either grep or sed. It is the venerable text processing language from which Perl derived some of its ideas.
| awk '{ if (NF > max) max = NF}' | Print the maximum number of fields on any input line | |
| awk ' length($0) > 80 ' | This program prints every line longer then 80 characters. The sole rule has a relational expression as its pattern, and has no action (so the default action, printing the record is used). | |
| awk ' NF > 0' | This program prints every line that has at least one field. This is an easy way to remove blank lines from a file, or rather to create another version of a file with blank lines removed. | |
| awk ' { if ( NF > 0 ) print }' | This program also prints every line that has at least 1 field. Here we allow the rule to match every line, then decide in the action whether to print. | |
| awk ' BEGIN { for (i = 1; i <=7; i++) print int(101 * rand()) }' |
This program prints 7 random numbers from 0 to 100 inclusive. | |
| ls -l FILES | awk '{x += $4} ; END {print "total bytes : " x}' | Obviously this will print the total bytes used by FILES | |
expand FILE | awk '{ if (x < length()) x = length() }; END{print " maximum line length is :" x}}' |
This program prints the maximum line length of FILE. The input is piped through the the 'expand' program to change tabs to spaces, so widths compared are actually the right-margin columns. | |
| awk 'BEGIN {FS=":"} {print $1 | "sort" }' /etc/passwd | This program prints a sorted list of the login names of all users. | |
| awk '{nlines++} END{print nlines}' | This program counts the lines in a file. | |
| awk 'END {print NR}' | This program also count the lines in a file but lets AWK do the work | |
| awk '{print NR, $0}' | This program adds line numbers to all its input files, similar to "cat -n" |
There is a GNU version of AWK known as GAWK. For more infomation on AWK see "The Awk Programming Language".