Created
April 19, 2014 13:24
-
-
Save robertchong/11084326 to your computer and use it in GitHub Desktop.
GROUP BY clause functionality in awk - bash
This file contains hidden or 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
#!/bin/bash | |
# | |
# This shell script demonstrates how to implement group by & aggregate functions in awk | |
# See http://www.unixcl.com/2008/09/group-by-clause-functionality-in-awk.html | |
# | |
# Input: A colon (:) delimited file tabulating Continents and numbers | |
# Output: Continents and values returned by aggregate functions Count(*), Total, Average | |
# | |
if [ $# -ne 1 ]; then | |
echo "Usage: $0 <filename>" | |
exit 1 | |
fi | |
inputFile=$1 | |
awk 'BEGIN{FS=":"; print "continent count total avg"} NR!=1 {a[$1]++;b[$1]=b[$1]+$2}END{for (i in a) printf("%s %10.0f %10.0f %10.2f\n", i, a[i], b[i], b[i]/a[i])} ' $inputFile | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Sample Usage: