brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: awk '{s+=$2} END {print s}' adds up a column of numbers

Awk
~/tips/tip-awk-sum-column-end

awk -F, '{s+=$2} END {print s}' costs.csv

Adds up all the numbers in one column of a file or command output.

A CSV export with amounts, the output of du, a log with response times: sooner or later you want the total of one column, and copying it into a spreadsheet for a single sum feels silly.

awk does it in one line:

awk -F, '{s+=$2} END {print s}' costs.csv

-F, splits each line on commas, {s+=$2} adds the second field to s for every line, and the END block runs once after the last line has been read, so the total gets printed only once. You don’t have to set s to zero first: an awk variable that was never set counts as zero.

Without -F, awk splits on runs of spaces and tabs, which suits command output. This one adds up the sizes in kilobytes of everything in a folder:

du -sk /mnt/user/appdata/* | awk '{s+=$1} END {print s " KB"}'

Swap print s for print s/NR and you have the average, because NR holds the number of lines read.

Now the caveats, and the first one is very Dutch. awk wants a dot as the decimal point, so an export with 1,5 style numbers gets read wrong (with -F, it’s even split in two). Convert the commas first, or with gawk try --use-lc-numeric. Second, big non-whole totals come out like 1.23457e+06, because print uses the %.6g format. Use printf "%.2f\n", s in the END block for a normal number. Also, a header line gets added too, but text counts as zero, so it does no harm.

Further reading: gawk(1) manual page

More Awk tips echo 'cost: 1,50 and 2,25' | awk '{n=gsub(/,/,"."); print n": "$0}' awk -F, 'NR>1 {print > ($2".csv")}' data.csv echo 20261201 | awk '{print substr($0,1,4)"-"substr($0,5,2)"-"substr($0,7,2)}' echo '2.5 3.7' | awk '{print int($1), int($2), sprintf("%.0f", $1)}' echo 'web1:8080,5' | awk -F'[:,]' '{print $1, $2, $3}' All Awk tips (17) All topics

Link