The sort Command
Data is rarely in the order you want. sort fixes that.
Basic Sort
By default, sort sorts alphabetically (by ASCII value).
Reverse Sort
Numeric Sort
This is crucial. Watch the difference:
Without -n, "10" comes before "2" because "1" < "2" alphabetically.
Always Use -n for Numbers
If you're sorting numbers and the order looks wrong, you probably forgot -n.
Sort by Column
Sort by a specific field:
-k2 = sort by second column (key 2).
With Different Delimiters
-t',' sets comma as delimiter.
Human-Readable Sizes
Sort file sizes like 1K, 2M, 3G:
-h understands K, M, G suffixes.
Remove Duplicates
-u removes duplicate lines (same as sort | uniq).
Case-Insensitive Sort
-f (fold case) treats upper and lowercase as equal.
Random Sort (Shuffle)
Great for randomizing data.
Stable Sort
Preserve original order for equal elements:
Real-World Examples
Find Largest Files
Top IP Addresses by Count
Sort CSV by Column 3
Why does `sort` put '10' before '2' without the -n flag?
Quick Reference
| Flag | Effect |
|---|---|
-n | Numeric sort |
-r | Reverse order |
-k N | Sort by column N |
-t | Set field delimiter |
-h | Human-readable sizes |
-u | Unique (remove duplicates) |
-f | Case-insensitive |
-R | Random shuffle |
Key Takeaways
- Default sort is alphabetical (ASCII order)
- Always use
-nfor numbers -k Nsorts by the Nth column-tsets the delimiter for columns-hhandles human-readable sizes (K, M, G)-rreverses the order
Next: removing duplicates with uniq.