Created
September 16, 2011 20:36
-
-
Save jotbe/1223087 to your computer and use it in GitHub Desktop.
CSV: Calculate totals of specific columns using awk
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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