sort -r: Reverse and Top-N Selection
sort -r reverses the comparison so output runs from highest to lowest.
To find the biggest or most frequent items, sort descending and take the head. -r flips whatever order you asked for.
What it does
sort -r reverses the result of the comparison, producing descending order. It applies on top of other modifiers, so -nr sorts numerically descending and a plain -r sorts strings in reverse collation order.
Common usage
sort -nr counts.txt | head -5 # five largest counts
uniq -c log.txt | sort -nr | head # most frequent lines
du -sh */ | sort -hr # largest dirs, human sizesOptions
| Flag | What it does |
|---|---|
| -r | Reverse the sort order |
| -n | Numeric: -nr is descending by value |
| -h | Human-readable sizes: -hr for largest first |
| -k <pos> | Reverse can attach per key, e.g. -k2,2nr |
In CI
The classic "top offenders" pipeline is sort | uniq -c | sort -nr | head. Build it once and reuse it for log frequency, file sizes, or test timings.
Common errors in CI
Reverse string order depends on the locale collation, so -r without LC_ALL=C can order punctuation and case unexpectedly; set LC_ALL=C for byte order. Forgetting -n in -r means a string reverse, so "9" sorts after "10"; use -nr for numbers.