What it does
sort reads all lines and prints them sorted. By default it sorts as text, from A to Z (following the language settings). With options it sorts numbers (-n), human sizes (-h), versions (-V), in reverse (-r), or on one column (-k).
Combined with uniq -c it makes "top lists" of anything: the most common IPs, errors, users.
How to write it
sort [OPTION]... [FILE]...Options 31
Most used
How to compare
What to compare
Order and output
Performance
Nothing matches this filter.
Examples 12
$ run as a normal user# run as root (or with sudo)
1Sort lines alphabetically
sort names.txtA to Z.
2Sort numbers the right way
sort -n numbers.txtWithout -n, 10 comes before 9 (text order).
3Biggest folders last (human sizes)
du -sh /var/* 2>/dev/null | sort -h-hunderstands K, M and G.4Sort /etc/passwd by UID
sort -t: -k3,3n /etc/passwdField separator
:, key = field 3 only, as a number.5Top list of anything
Count each value, the most common first.
6The IPs with the most requests in a web log
The first step when a site is slow or attacked.
7Unique values only
sort -u hosts-from-many-files.txtSame as
sort | uniq.8Sort version numbers
ls /srv/releases | sort -Vv1.2, v1.10, v2.0 in the right order.
9Sort by the second column, reverse
sort -k2,2nr scores.txtHighest score first.
10Sort a file in place
sort -o users.txt users.txt-ocan write to the same file safely (redirect>cannot).11Check if a file is sorted
sort -c list.txt && echo sortedExit code 0 when sorted.
12Sort a huge file faster
sort -S 2G --parallel=4 -T /var/tmp big.csv > big-sorted.csvMore memory and threads; temp files on a disk with space.
Nothing matches this filter.
Watch out
- Text order depends on the language (LANG). For a byte-order sort in scripts use
LC_ALL=C sort. sort file > fileempties the file first. Use-o file.- Without
,Nin-k, the key goes to the end of the line: use-k2,2for only field 2.
Tips to remember
- n = numbers, h = sizes, V = versions, r = reverse, u = unique, k = column, t = separator.