Last active
October 3, 2024 13:07
-
-
Save lewisd32/4be2605400acf0bb562d to your computer and use it in GitHub Desktop.
Calculate percentile in bash
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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" |
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
Great idea with (n + 99) / 100 👍
You may use "sed -n ${count}p $tmp" instead of "head | tail"