The GNU Awk User's Guide - Word Sorting Go to the first , previous , next , last section, table of contents . The following awk program prints the number of occurrences of each word in its input. It illustrates the associative nature of awk arrays by using strings as subscripts. Finally, it shows how awk can be used in conjunction with other utility programs to do a useful task of some complexity with a minimum of effort.
Some explanations follow the program listing.
The first rule, because it has an empty pattern, is executed on every line of the input. For each input word, an element of the array freq is incremented to reflect that the word has been seen an additional time. The second rule, because it has the pattern END , is not executed until the input has been exhausted. It prints out the contents of the freq table that has been built up inside the first action. This means that punctuation characters count as part of words.