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 -nSort by file size
cat /etc/passwd | cut -d: -f1 | sort | head -10
sort file.txtAlphabetical sort
sort -r file.txtReverse sort
sort -n numbers.txtNumeric sort
sort -k2 file.txtSort by 2nd column
sort -u file.txtSort and remove duplicates
sort -t: -k3 -n /etc/passwdSort passwd by UID
sort file.txt | uniqRemove duplicates
sort file.txt | uniq -cCount occurrences
sort file.txt | uniq -dShow only duplicates
sort file.txt | uniq -uShow 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 -3Requests per address, most first
sort -k2 -rnBy the 2nd column, as numbers, highest first
du -sh /* 2>/dev/null | sort -rh | headTop-level space hogs, sorted
Lessons that use sort
- Pipes & Redirection
- sort & uniq — Sorting and Deduplication
- cut & tr — Extracting Columns
- df & du — Disk Usage
- Reading the Logs
- Project: Daily Log Report
- Project: Sales Report from a CSV
- Mission: Disk Full