Skip to content

Instantly share code, notes, and snippets.

@Sibirtsev
Forked from lewisd32/percentile.sh
Created August 18, 2016 04:54
Show Gist options
  • Save Sibirtsev/bc09a5f7599e06e1e33629f9092d20f5 to your computer and use it in GitHub Desktop.
Save Sibirtsev/bc09a5f7599e06e1e33629f9092d20f5 to your computer and use it in GitHub Desktop.
Calculate percentile in bash
#!/bin/bash
# stdin should be integers, one per line.
percentile=$1
tmp="$(tempfile)"
total=$(sort -n | tee "$tmp" | wc -l)
# (n + 99) / 100 with integers is effectively ceil(n/100) with floats
count=$(((total * percentile + 99) / 100))
head -n $count "$tmp" | tail -n 1
rm "$tmp"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment