The sort command

sort lines of text files 22 examples from the lessons of the IVski Linux Playground — try them in the terminal next to them.

Options in the examples

-n, --numeric-sort
compare according to string numerical value; see full documentation for supported strings
-r, --reverse
reverse the result of comparisons
-k, --key=KEYDEF
sort via a key; KEYDEF gives location and type
-h, --human-numeric-sort
compare human readable numbers (e.g., 2K 1G)
-u, --unique
output only the first of lines with equal keys; with -c, check for strict ordering

Examples

ls -la | sort -k5 -n

Sort by file size

cat /etc/passwd | cut -d: -f1 | sort | head -10
sort file.txt

Alphabetical sort

sort -r file.txt

Reverse sort

sort -n numbers.txt

Numeric sort

sort -k2 file.txt

Sort by 2nd column

sort -u file.txt

Sort and remove duplicates

sort -t: -k3 -n /etc/passwd

Sort passwd by UID

sort file.txt | uniq

Remove duplicates

sort file.txt | uniq -c

Count occurrences

sort file.txt | uniq -d

Show only duplicates

sort file.txt | uniq -u

Show only unique lines

history | awk '{print $2}' | sort | uniq -c | sort -rn | head -10
cat access.log | awk '{print $1}' | sort | uniq -c | sort -rn
cut -d: -f7 /etc/passwd | sort | uniq -c
du -sh /var/* | sort -rh | head -10
awk '{print $1}' /var/log/nginx/access.log | sort | uniq -c | sort -rn | head -3
awk '{print $9}' /var/log/nginx/access.log | sort | uniq -c
awk '$9 == 404 {print $7}' /var/log/nginx/access.log | sort | uniq -c | sort -rn
awk '{print $1}' ~/logs/access.log | sort | uniq -c | sort -rn | head -3

Requests per address, most first

sort -k2 -rn

By the 2nd column, as numbers, highest first

du -sh /* 2>/dev/null | sort -rh | head

Top-level space hogs, sorted

Lessons that use sort

Related commands