sort Cheatsheet
Basic Syntax
Core sort command forms.
| Command | Description |
|---|---|
sort file.txt |
Sort lines alphabetically (ascending) |
sort -r file.txt |
Sort lines in reverse order |
sort -n file.txt |
Sort numerically |
sort -nr file.txt |
Sort numerically, largest first |
sort file1 file2 |
Merge and sort multiple files |
Sort by Field
Sort lines by one column or key.
| Command | Description |
|---|---|
sort -k2 file.txt |
Sort by second field |
sort -k2,2 file.txt |
Sort using only field 2 as key |
sort -t: -k3,3n /etc/passwd |
Sort by UID field in /etc/passwd |
sort -t, -k1,1 data.csv |
Sort CSV by first column |
sort -k3,3 -k1,1 file.txt |
Secondary sort: key 3, then key 1 |
Numeric and Human Sizes
Handle numbers and size suffixes correctly.
| Command | Description |
|---|---|
sort -n numbers.txt |
Numeric sort |
sort -g values.txt |
General numeric sort (floats/scientific notation) |
sort -h sizes.txt |
Sort human-readable sizes (K, M, G) |
| `du -sh /var/* | sort -h` |
sort -V versions.txt |
Natural version sort (1.9 before 1.10) |
Unique and Check
Detect duplicates and verify sorted input.
| Command | Description |
|---|---|
sort -u file.txt |
Sort and remove duplicate lines |
| `sort file.txt | uniq` |
| `sort file.txt | uniq -c` |
sort -c file.txt |
Check if file is sorted |
sort -C file.txt |
Quiet sorted-check (status code only) |
In-Place and Output
Safe ways to write sorted results.
| Command | Description |
|---|---|
sort file.txt > sorted.txt |
Write output to a new file |
sort -o file.txt file.txt |
Sort in place safely |
sort -o out.txt in.txt |
Write sorted output with -o |
sort -T /tmp bigfile.txt |
Use temp directory for large sorts |
LC_ALL=C sort file.txt |
Byte-order sort for predictable locale behavior |
Common Pipelines
Practical combinations with other commands.
| Command | Description |
|---|---|
| `grep -Eo ‘[[:alnum:]_]+’ file.txt | sort |
| `cut -d’,’ -f2 data.csv | sort` |
| `sort access.log | uniq -c |
| `ps -eo user= | sort |
| `find . -type f | sort` |
Troubleshooting
Quick checks for common sort issues.
| Issue | Check |
|---|---|
| Numbers sorted as text | Add -n (or -g for floats) |
| Size values ordered incorrectly | Use -h for human-readable sizes |
| Unexpected uppercase/lowercase order | Use -f or set locale with LC_ALL=C |
| File was emptied after sorting | Do not use sort file > file; use sort -o file file |
| Different results across systems | Verify locale and use explicit key options (-k) |
Related Guides
Use these guides for full sorting and text-processing workflows.
| Guide | Description |
|---|---|
sort Command in Linux
|
Full sort guide with examples |
uniq |
Remove and count duplicate lines after sorting |
head Command in Linux
|
Show the first lines of output |
wc Command in Linux
|
Count lines, words, and bytes |
cut Command in Linux
|
Extract fields from text |
grep Command in Linux
|
Search and filter matching lines |
