Skip to content

Instantly share code, notes, and snippets.

@jotbe
Created September 16, 2011 20:36
Show Gist options
  • Save jotbe/1223087 to your computer and use it in GitHub Desktop.
Save jotbe/1223087 to your computer and use it in GitHub Desktop.
CSV: Calculate totals of specific columns using awk
# Sample usage:
# $ gawk -F, -v coli=9 -v colc=10 -f calc_totals.awk < file.csv
BEGIN{
# Separator for the output
sep = ","
# coli is the position of the imps column.
# It is passed as an arg, eg. -v coli=9
if (coli > 0) {
fields["imps"] = coli
}
# colc is the position of the imps column.
# It is passed as an arg, eg. -v coli=10
if (colc > 0) {
fields["clicks"] = colc
}
totals["imps"] = 0
totals["clicks"] = 0
}
{
row = ""
for (i = 0; i <= NF; i++){
for (key in fields){
if(i == fields[key]){
if (key in totals) {
# Add to sum
totals[key] = totals[key] + $fields[key]
}
}
}
}
}
END{
print "Impressions:", totals["imps"]
print "Clicks:", totals["clicks"]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment