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[$1]+=$2' adds up a column per group

Awk
~/tips/tip-awk-group-sum-array

awk -F, 'NR>1 {s[$2]+=$3} END {for (k in s) print k, s[k]}' orders.csv

Totals a number column separately for each value in another column, like a GROUP BY.

Adding up a whole column is one thing. Getting a total per customer, per host or per day is where awk’s arrays come in.

awk -F, 'NR>1 {s[$2]+=$3} END {for (k in s) print k, s[k]}' orders.csv

For every row after the header, the amount in column 3 is added to an array entry named after column 2. So all rows of customer 1 add up in s["1"]. In the END block, the loop prints one line per group. In the example, customer 1 comes out at 17 and the others at their single amounts.

Counting works the same way with c[$2]++, and you can keep both in one pass to print an average: s[k]/c[k].

The thing that bites is the order. for (k in s) has no defined order, and it really differs per implementation: macOS awk, mawk and gawk can each print the groups in a different order. I’d pipe the result through sort when the order matters:

awk -F, 'NR>1 {s[$2]+=$3} END {for (k in s) print k, s[k]}' orders.csv | sort -k2,2nr

That puts the biggest total on top. Also, a quoted CSV field with a comma inside will shift the columns, because -F, knows nothing about quotes.

Further reading: GNU awk manual, POSIX awk specification

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