Skip to content
Latchkey

awk Average a Column: Mean of a Field

awk computes an average by accumulating a column and dividing by the count of rows in END.

Mean latency or mean coverage across runs is sum divided by count. The subtlety is counting only the rows you summed and guarding against divide-by-zero.

What it does

Accumulate the field into sum and a counter n in the main block, then in END print sum/n. Using a dedicated counter (rather than NR) keeps the average correct when you skip headers or filter rows.

Common usage

Terminal
# mean of column 2
awk '{sum += $2; n++} END {if (n) print sum/n}' latency.txt
# average skipping the header row
awk 'NR>1 {sum += $3; n++} END {print sum/n}' results.csv
# formatted to two decimals
awk '{s += $1; n++} END {printf "%.2f\n", s/n}' nums.txt

Patterns

SnippetWhat it does
sum+=$2; n++Accumulate value and row count together
END{print sum/n}Print the mean after all rows
if (n) print sum/nGuard against divide-by-zero on empty input
NR>1{...n++}Count only non-header rows
printf "%.2f", s/nRound the mean to two decimal places

In CI

Always guard the division with if (n) or n? so empty input does not crash or print inf; an empty metrics file is common when a job produced no data. Use your own counter n rather than NR when rows are filtered, or the denominator is wrong.

Common errors in CI

"awk: division by zero attempted" (gawk) or "inf"/"-nan" (mawk) means n was 0 on empty input; wrap the print in if (n). Dividing sum by NR instead of n overcounts when you skipped a header, dragging the average down. A %.2f with a non-numeric column prints 0.00 because the field coerced to 0.

Related guides

Run this faster and cheaper on Latchkey managed runners. Start free →