Skip to content

Instantly share code, notes, and snippets.

@mkf
Created September 5, 2020 15:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mkf/395f1a5aee2b8f8ed5abb3f3f3a6fc0e to your computer and use it in GitHub Desktop.
Save mkf/395f1a5aee2b8f8ed5abb3f3f3a6fc0e to your computer and use it in GitHub Desktop.
averaging grouped values, rounding upwards
#!/usr/bin/env bash
unset key
cat data.csv | # reads from data.csv
tail -n +2 | # removes first line
tr -d ' ' | # removes all spaces
cut -d ',' -f1,3 | # takes first and third field
# from here on this program:
# calling the right-hand field (string) the key,
# and the left-hand field (positive integers) the values,
# groups by key, returning a rounded-upwards average of the values,
# as, in order, key and the average, separated by a tab character
tr ',' '\t' | # replaces commas with tabs
uniq -f 1 --group=append |
# ↑ groups by key, by appending a blank line after each key-group
while read -r value lkey
# fits each group in a single
# "key value value value..." line
do
if [[ ! -z $value ]]
then
if [[ ! -v key ]]
then
key=$lkey; echo -ne "$key"
elif [[ $lkey != $key ]]
then
exit 13
fi
echo -ne "\t${value}"
else
unset key
echo
fi
done |
awk \
# averages the values in each line,
# rounding the average up.
'{ sum=0; num=0;
for (i=2;i<=NF;i++)
{sum+=$i; num++ } ;
sum=sum/num ;
num=int(sum) ;
sum=(sum>num ? num+1 : num) ;
printf "%s\t%d\n", $1, sum }'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment