Skip to content

Instantly share code, notes, and snippets.

@ataliba
Created March 11, 2019 21:06
Show Gist options
  • Save ataliba/bf6c446bf7a9cd2dcf50caf4e1e79b3d to your computer and use it in GitHub Desktop.
Save ataliba/bf6c446bf7a9cd2dcf50caf4e1e79b3d to your computer and use it in GitHub Desktop.
# Bucketize stdin to nearest multiple of argv[1], or 10 if no args given.
# "nearest" means 0..4.999 -> 0, 5..14.999 -> 10, etc.
# Usage:
# while true ; do echo $[ 1 + $[ RANDOM % 100 ]]; done | head -99 | bucket.sh 8
awk -v multiple="${1:-10}" '
function bucketize(a) {
# Round to the nearest multiple of "multiple"
# (nearest... i.e. may round up or down)
return int((a + (multiple/2)) / multiple) * multiple;
}
# All lines get bucketized.
{ arr[bucketize($1)]++ }
# When done, output the array.
END {
for (i in arr) {
print i, arr[i]
}
}
' | sort -k2n,2 -k1n,1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment