Skip to content

Instantly share code, notes, and snippets.

@opplatek
Last active August 3, 2023 08:17
Show Gist options
  • Save opplatek/0dab8a4c286dcaea4701feec2b32ce19 to your computer and use it in GitHub Desktop.
Save opplatek/0dab8a4c286dcaea4701feec2b32ce19 to your computer and use it in GitHub Desktop.
Calculate median and mean in AWK from a specific column
#!/bin/bash
#
# Calculate median and mean with AWK from a specific column
#
COL_NUMBER=1 # column number with values to calculate median/mean from
MEAN=$(echo -e "1\n10\n5\n4\n3" | awk -v N=$COL_NUMBER '{ sum += $N } END { if (NR > 0) print sum / NR }')
MEDIAN=$(echo -e "1\n10\n5\n4\n3" | cut -f${COL_NUMBER} | sort -n | awk ' { a[i++]=$1; } END { x=int((i+1)/2); if (x < (i+1)/2) print (a[x-1]+a[x])/2; else print a[x-1]; }')
echo $MEAN
#4.6
echo $MEDIAN
#4
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment