shell · difficulty ◆
sort — sort lines of text
Order the chaos — sort lines by content, number, or any field you choose.
$ sortWhat it does
sort reads lines of text from a file or stdin and writes them back in sorted order. By default it sorts lexically (byte-wise, like a dictionary), but with -n it compares numbers, with -k it sorts by a specific field, and with -r it reverses the order. Because it works on streams, it is the natural partner of every other text tool in the pipeline.
Why it matters
sort is what turns raw output into something readable. Want the biggest files first, the most common log message, or an alphabetical index? sort is the first step. Teamed with uniq (to collapse duplicates) and head or tail (to trim to the extremes), it becomes a tiny data-analysis engine that runs entirely on the command line with no spreadsheet in sight.
Example
$ sort /etc/passwd | head -3daemon:x:1:1:daemon:/usr/sbin:/usr/sbin/nologin
bin:x:2:2:bin:/bin:/usr/sbin/nologin
nobody:x:65534:65534:nobody:/nonexistent:/usr/sbin/nologinsort alone sorts alphabetically; head -3 shows just the first few lines of the result.
$ du -h --max-depth=1 | sort -h -r | head -512G ./node_modules
1.2G ./.git
340M ./dist
22M ./src
4.0K ./.env-h sorts by human-readable sizes and -r reverses, so the biggest directory appears first.
Common flags
- -n
- sort numerically instead of lexically (so 10 comes after 2)
- -r
- reverse the sort order
- -k N
- sort by the Nth whitespace-separated field
- -t CH
- set the field separator character (used with -k), e.g. -t: for /etc/passwd
- -h
- sort by human-readable sizes like 2K, 300M, 12G
- -u
- output only unique lines (like sort then uniq)
- -f
- fold case — ignore case differences while sorting
History
Origin
sort has been part of Unix since the very first editions in the early 1970s, alongside the other early text tools like grep and wc. It was designed to sort files too large to fit in memory, using external merge sorting, which is why it can handle millions of lines on modest hardware — a capability that remains deeply useful today.
Fun fact
The default lexical sort compares bytes, which is why '10' sorts before '2' unless you pass -n. This exact gotcha trips up countless scripts. GNU sort also supports locale-aware sorting and a stable mode (-s) that preserves the original order of equal lines — handy when you chain multiple sorts.