Skip to content

Instantly share code, notes, and snippets.

@mkf
Created Sep 5, 2020
Embed
What would you like to do?
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