Skip to content
Latchkey

awk Sum a Column: Total a Numeric Field

awk accumulates a column into a variable as it reads each line and prints the total in END.

Totaling file sizes, test counts, or request durations is the canonical awk arithmetic task. Add the field to an accumulator per line, print it once at the end.

What it does

In the main block, sum += $N adds the Nth field of each line to the accumulator sum, coercing the field to a number. Because variables start at 0, no initialization is needed. END prints the final total once.

Common usage

Terminal
# total of column 1
awk '{sum += $1} END {print sum}' sizes.txt
# total bytes from ls -l (5th column)
ls -l | awk 'NR>1 {sum += $5} END {print sum}'
# sum only matching rows
awk '/PASS/ {sum += $3} END {print sum}' results.txt
# sum with a label
awk '{s += $2} END {printf "total: %d\n", s}' counts.txt

Patterns

SnippetWhat it does
sum += $1Add field 1 of the current line to sum
END{print sum}Print the accumulated total once
NR>1{sum+=$5}Skip a header row, then sum field 5
/PASS/{sum+=$3}Sum only on matching lines
$2+0Force numeric coercion when a field has units

In CI

To emit a total as a step output: TOTAL=$(awk '{s+=$1} END{print s}' sizes.txt); echo "total=$TOTAL" >> "$GITHUB_OUTPUT". The accumulator handles missing trailing newlines fine, unlike some shell loops.

Common errors in CI

A total that comes out as 0 means the field is non-numeric (wrong column or wrong FS), since a non-numeric field coerces to 0; check -F and the column index. Fields with units like "12MB" sum their numeric prefix (12), which may not be what you want; strip units with gsub first. An empty input prints a blank line in mawk unless you print sum+0.

Related guides

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