Skip to content

sort Command Cheat Sheet

sort sorts lines of text files. It is an incredibly powerful tool capable of handling files larger than system memory.


Synopsis

sort [OPTION]... [FILE]...

Basic Sorting

Ascending (Default)

Sorts alphabetically (A-Z).

sort file.txt

Reverse (-r)

Sorts Z-A.

sort -r file.txt

Numeric Sorting (-n)

By default, 10 comes before 2 because 1 < 2. Use -n to sort by numerical value.

sort -n numbers.txt

Human Numeric Sort (-h)

Sorts sizes like 2K, 1M, 3G correctly.

du -h | sort -h
This is one of the most useful combinations.


Column Sorting

Specific Key (-k)

Sort by the 2nd column.

sort -k 2 file.txt

Multiple Keys

Sort by Column 2, then by Column 3 numerically.

sort -k 2,2 -k 3,3n file.txt

Custom Delimiter (-t)

If columns are separated by , (CSV) instead of spaces.

sort -t ',' -k 2 file.csv

Manage Duplicates

Unique (-u)

Output only the first of an equal run.

sort -u file.txt
(Equivalent to sort file.txt | uniq).


Performance

Check if Sorted (-c)

Exits with 0 if sorted, 1 if not. Doesn't print output.

sort -c file.txt

Merge Sorted Files (-m)

Merges files that are already sorted. This is much faster than sorting them all again.

sort -m sorted1.txt sorted2.txt

Random Sort (-R)

Shuffle lines randomly.

sort -R file.txt

Notes

  • Locale: Sorting order depends on LC_COLLATE. To count strictly by byte value (ASCII), use export LC_ALL=C.
  • Stable Sort (--stable): Preserves the original order of lines that compare as equal.