$_ CLI In Depth
Learning progress 0%
lesson text-processing regex awk

awk Aggregation & Reports

5 min read Module 6: Text Processing: grep, sed & awk Updated Dec 5, 2026
Cheat Sheet
0:00 / 3:26

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.

BASH2 lines
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.txt

The 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.

Warning

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.

BASH2 lines
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 | sort

The 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.

BASH1 lines
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] }'| sort

The 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.

BASH1 lines
awk ' n[$1]++ } END { for (u in n) print n[u], u }'requests.txt | sort -rn

The 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.

BASH1 lines
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.

BASH1 lines
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 | sort

The 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.

sed and awk, one record at a time

Visualizer

sed edits one line at a time through a buffer. awk splits each record into fields, tests a pattern, runs an action, and can total values in an array.

1 / 5
sed: one input line at a time
input lineafter s/cat/dog/printed

sed reads one input line at a time into a buffer called the pattern space. The commands run in order on that buffer, and at the end of the cycle the buffer is printed unless a command deleted it.

printf 'the cat sat\na cat\ncat cat\n' | sed -e 's/cat/dog/' -e '2d'
Terminal lab · 2 steps · real Linux in your browser

Totals and averages in awk

Count requests per user and compute averages per key.

01
Count lines per user
requests.txt holds a user and a method on each line. Count the lines per user and sort the output: ``bash awk '{ n[$1]++ } END { for (u in n) print u, n[u] }' requests.txt | sort > counts.txt ``
Show hint for step 1
Use an array indexed by the first field, and print it in the END block.
02
Average per key
latency.txt holds a service name and a time on each line. Compute the average per service with one decimal place, sorted by name: ``bash awk '{ s[$1] += $2; c[$1]++ } END { for (k in s) printf "%s avg=%.1f\n", k, s[k] / c[k] }' latency.txt | sort > avg.txt ``
Show hint for step 2
Keep a sum and a count per key, and divide in the END block.
Check yourself Question 1 of 4
Concept Check Unset array elements recall

In awk, what does an array element that was never assigned evaluate to when it is used as a number?

Recap & Key Takeaways

Associative arrays let awk keep a running count or sum for every distinct key, created the first time it is used.
Print aggregates in an END block, and sort the output explicitly because the order of for-in is not defined.
Put the count or sum first in each output line when you plan to rank with sort -rn.
Guard divisions in averages, and use printf to format numbers with a fixed number of decimal places.
Was this lesson helpful? Spot an issue or have a suggestion? Let us know on GitHub.
Report an issue