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
© 2005 The SCO Group, Inc. All rights reserved.
SCO OpenServer Release 6.0.0 -- 02 June 2005