Skip to content

Instantly share code, notes, and snippets.

@lewisd32
Last active November 20, 2023 07:47
Show Gist options
  • Star 20 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save lewisd32/4be2605400acf0bb562d to your computer and use it in GitHub Desktop.
Save lewisd32/4be2605400acf0bb562d 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"
@vlinevych
Copy link

Great idea with (n + 99) / 100 👍

You may use "sed -n ${count}p $tmp" instead of "head | tail"

@imarko
Copy link

imarko commented Apr 27, 2020

Made a one-liner version of this for fun. The trick is to count the number of lines and then select the right line based on that count within the same pipeline and without temp files:
cat mynumbers.txt|(percentile=95; (sort -n;echo)|nl -ba -v0|tac|(read count;cut=$(((count * percentile + 99) / 100)); tac|sed -n "${cut}s/.*\t//p"))

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment