TIL: awk - Summing a column on the command line
Every now and then I need to sum the values of a column in some output (file sizes, bytes transferred, error counts in a log...) and I always ended up dumping it into a spreadsheet or writing a script.
Today I learned (TIL) that this can be solved directly with awk in a single line.
The idea
awk reads each line of input and automatically splits it into fields
separated by whitespace. Each field is available as $1, $2, $3...
and the whole line as $0.
To sum column 5 of the ls -l output (size in bytes):
ls -l | awk '{ sum += $5 } END { print sum }'
{ sum += $5 }runs for every line.END { print sum }runs only once, after all the input has been read.
The sum variable doesn't need to be declared or initialized, awk starts
it at 0.
Changing the separator
By default the separator is whitespace. For other formats just use
-F. Summing the third column of a CSV:
awk -F',' '{ sum += $3 } END { print sum }' data.csv
To read /etc/passwd and sum the UIDs (third field, separated by :):
awk -F':' '{ sum += $3 } END { print sum }' /etc/passwd
Filtering before summing
Since the { ... } block accepts a condition in front of it, you can sum only
what matters. For example, summing the size of .md files only:
ls -l *.md | awk '/\.md$/ { sum += $5 } END { print sum }'
Or summing bytes only for requests with status 200 in an nginx-format
log:
awk '$9 == 200 { sum += $10 } END { print sum }' access.log
Bonus: average
Since we are counting anyway, you can get the average in the same pass using
NR (current line number, which in END holds the total number of lines):
awk '{ sum += $1 } END { print sum / NR }' numbers.txt
For more information man awk.