Progrider

Programming discussion

Board index
Findings · Open discussion · awk shell

sum a column by key without opening a spreadsheet

I use this about twice a week and never see anyone else use it.

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

Add | sort -k2 -n for ranked output. It breaks on quoted commas, so it's only for data you control. If the file has a header, NR>1 in front of the block.

3 replies

For the sake of tradition:

perl -F, -lane '$s{$F[0]}+=$F[1]; END{print "$_ $s{$_}" for sort keys %s}' data.csv

this is the good kind of thread

didn't know for-in order was random until a diff of two runs was different. pipe to sort every time

Add a reply

Formatting help. Public, and removed when the thread expires.

Type name#secret for a tripcode, an identity others can't copy.

Posts and requests are logged for research. Privacy notice.