The sort Command

Data is rarely in the order you want. sort fixes that.

Basic Sort

Terminal
$cat names.txt
charlie alice bob
$sort names.txt
alice bob charlie

By default, sort sorts alphabetically (by ASCII value).

Reverse Sort

Terminal
$sort -r names.txt
charlie bob alice

Numeric Sort

This is crucial. Watch the difference:

Terminal
$echo -e '10\n2\n1\n20' | sort
1 10 2 20
$echo -e '10\n2\n1\n20' | sort -n
1 2 10 20

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:

Terminal
$cat scores.txt
alice 95 bob 87 charlie 92
$sort -k2 -n scores.txt
bob 87 charlie 92 alice 95

-k2 = sort by second column (key 2).

With Different Delimiters

Terminal
$cat data.csv
alice,95,engineering bob,87,marketing charlie,92,sales
$sort -t',' -k2 -n data.csv
bob,87,marketing charlie,92,sales alice,95,engineering

-t',' sets comma as delimiter.

Human-Readable Sizes

Sort file sizes like 1K, 2M, 3G:

Terminal
$du -h /var/log/* | sort -h | tail -5
4.0K /var/log/apt 100K /var/log/journal 2.5M /var/log/syslog 15M /var/log/nginx 50M /var/log/mysql

-h understands K, M, G suffixes.

Remove Duplicates

Terminal
$sort -u names.txt
(sorted and unique)

-u removes duplicate lines (same as sort | uniq).

Case-Insensitive Sort

Terminal
$echo -e 'Bob\nalice\nCharlie' | sort
Bob Charlie alice
$echo -e 'Bob\nalice\nCharlie' | sort -f
alice Bob Charlie

-f (fold case) treats upper and lowercase as equal.

Random Sort (Shuffle)

Terminal
$sort -R names.txt
(random order each time)

Great for randomizing data.

Stable Sort

Preserve original order for equal elements:

Terminal
$sort -s -k1 data.txt
(maintains relative order within same key)

Real-World Examples

Find Largest Files

Terminal
$ls -lh | sort -k5 -h -r | head
(biggest files first)

Top IP Addresses by Count

Terminal
$cut -d' ' -f1 access.log | sort | uniq -c | sort -rn | head
1523 192.168.1.1 892 10.0.0.5 234 172.16.0.1

Sort CSV by Column 3

Terminal
$sort -t',' -k3 data.csv
(sorted by third column)
Knowledge Check

Why does `sort` put '10' before '2' without the -n flag?

Quick Reference

FlagEffect
-nNumeric sort
-rReverse order
-k NSort by column N
-tSet field delimiter
-hHuman-readable sizes
-uUnique (remove duplicates)
-fCase-insensitive
-RRandom shuffle

Key Takeaways

  • Default sort is alphabetical (ASCII order)
  • Always use -n for numbers
  • -k N sorts by the Nth column
  • -t sets the delimiter for columns
  • -h handles human-readable sizes (K, M, G)
  • -r reverses the order

Next: removing duplicates with uniq.