Arrays keyed by text
awk arrays are associative. An index can be a number or a string, and an array element is created the first time you assign to it. A line such as count[$1]++ therefore keeps a counter for every distinct value in the first field. Unset elements read as empty, which is zero when used as a number, so you do not have to initialize them.
This is the building block for every report in this unit. The pattern is always the same: pick a key from the line, add a value to the array under that key, and then print the array in the END block.
Counting by key
The example counts how many lines each user has in a small access list. The first field is the key, and the program increments a counter for it.
printf 'nn GET\nbob POST\nann GET\nann POST\n'> requests.txt
awk ' n[$1]++ } END { for (u in n) print u, n[u] }'requests.txtThe output lists ann 3 and bob 1. The order of a for (k in array) loop is not defined by POSIX, so the lines may come out in either order. Pipe the output to sort when the order matters, which is the subject of the next step.
Do not rely on the order of a for-in loop. Two runs of the same program can print the keys in different orders, so sort the output explicitly.
Summing a column
A sum works the same way as a count, but it adds a field value instead of one. The example adds the byte counts in the second column for each path.
printf 'index 512\n/about 128\n/index 1024\n'> bytes.txt
awk ' total[$1] += $2 } END { for (p in total) print p, total[p] }'bytes.txt | sortThe output is /about 128 and /index 1536, after sorting. The field value is converted to a number when it is used in arithmetic, so the values in the input can be plain text that looks like numbers.
Averages and totals
An average needs two arrays, or one array plus a count. The usual approach is to keep the sum and the count per key, and divide in the END block. Dividing by zero is an error in awk, so guard the division when a key may have no values.
printf 'eb 120\nweb 80\ndb 300\n'| awk ' s[$1] += $2; c[$1]++ } END { for (k in s) printf "%s avg=%.1f\n", k, s[k] / c[k] }'| sortThe output is db avg=300.0 and web avg=100.0. The printf format %.1f rounds to one decimal place, which keeps report columns consistent.
Ranking the result
awk can rank inside the program, but a common shell approach is simpler to read: let awk produce key and value pairs, then sort them numerically. The example ranks users by request count, highest first.
awk ' n[$1]++ } END { for (u in n) print n[u], u }'requests.txt | sort -rnThe count comes first in the output so that sort -rn can rank on it. The result is 3 ann followed by 1 bob. Putting the count first is the trick that makes numeric sorting of report lines easy.
Counting distinct values
An array also answers a different question: how many distinct values appear. The trick is to store each value as a key, and then count the keys with a loop. The array holds each value once, no matter how often it appears, so counting the entries counts the distinct values.
printf 'ET\nPOST\nGET\nPUT\n'| awk ' seen[$1] = 1 } END { n = 0; for (m in seen) n++; print n, "distinct methods" }'The output is 3 distinct methods. The counting happens in the END block, because it is the only place where every line has been seen. This pattern is useful for questions such as how many distinct clients visited a site today.
Be aware of the memory cost. Every distinct key is kept in memory until the program ends, so a field with millions of unique values, such as a session identifier, can exhaust memory on a small machine. For those cases, a sort and uniq pipeline uses temporary files and scales further.
Think about the data before you choose the aggregate. A count tells you how often something happened, a sum tells you how much of a quantity there was, and an average can hide a few very large or very small values. When the average looks odd, print the count next to it, because a mean based on one sample can mislead as much as a wrong sum. Reporting the count with every aggregate makes the numbers easier to check.
Printing a report
A report is usually a heading, one line per key, and a total. Put the heading in BEGIN, the rows in the END loop, and the total after the loop. Use printf for aligned columns, as in the previous unit.
awk 'EGIN { printf "%-6s %5s\n", "user", "reqs" } { n[$1]++; t++ } END { for (u in n) printf "%-6s %5d\n", u, n[u]; printf "%-6s %5d\n", "total", t }'requests.txt | sortThe sort in this pipeline sorts the heading along with the rows, so it is only a rough tidy-up for this example. In a real report you would sort the rows inside awk, or sort before printing the total. The point of the example is that a single awk program can produce a complete, aligned report from a raw log.