DOC HOME SITE MAP MAN PAGES GNU INFO SEARCH PRINT BOOK
 
Programming with awk

Word frequencies

Our first example illustrates associative arrays for counting. Suppose you want to count the number of times each word appears in the input, where a word is any contiguous sequence of non-blank, non-tab characters. The following program prints the word frequencies, sorted in decreasing order.

   { for (w = 1; w <= NF; w++) count[$w]++ }
   END  { for (w in count) print count[w], w | "sort -nr" }
The first statement uses the array count to accumulate the number of times each word is used. Once the input has been read, the second for loop pipes the final count along with each word into the sort command.
Next topic: Accumulation
Previous topic: Generating reports

© 2004 The SCO Group, Inc. All rights reserved.
UnixWare 7 Release 7.1.4 - 27 April 2004