Skip to content

Instantly share code, notes, and snippets.

@gkalabin
Forked from lewisd32/percentile.sh
Last active August 29, 2015 14:27
Show Gist options
  • Save gkalabin/03264c94c349d655743b to your computer and use it in GitHub Desktop.
Save gkalabin/03264c94c349d655743b to your computer and use it in GitHub Desktop.
Calculate percentile in bash
#!/bin/bash
# args are percentiles, stdin - integers one per line
set -o errexit
set -o nounset
set -o pipefail
tmp="$(mktemp -t percentile)"
trap "rm -f \"$tmp\"" EXIT
total=$(sort -n | tee "$tmp" | wc -l)
for percentile in "$@"; do
# (n + 99) / 100 with integers is effectively ceil(n/100) with floats
count=$(((total * percentile + 99) / 100))
head -n $count "$tmp" | tail -n 1
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment