sort - Put Lines in Order
Learn sort for ordering text. Alphabetical, numerical, by column - essential for data analysis pipelines.
sort: Bring Order to Chaos
You have a file with data in random order. You want it sorted. That's literally what sort does:
sort names.txt
Alphabetical order. Done.
Alphabetical vs Numerical
Here's where people get tripped up. By default, sort orders alphabetically:
1
10
2
3
That's "correct" alphabetically (1 comes before 2, and 10 starts with 1). But if you want numerical order:
sort -n numbers.txt
Now you get 1, 2, 3, 10.
Reverse Order
sort -r file.txt
Z to A, or highest to lowest with -rn.
Sorting by Column
Real data has multiple columns. Sort by the second one:
sort -k2 data.txt
Sort by the third column numerically:
sort -k3 -n scores.txt
Custom Delimiters
If your columns aren't space-separated:
sort -t',' -k2 data.csv
The -t',' sets comma as the delimiter.
Remove Duplicates While Sorting
sort -u file.txt
Like sort | uniq but in one command.
The Classic Pipeline
This pattern appears everywhere:
cat data.txt | sort | uniq -c | sort -rn | head
Read → sort → count duplicates → sort by count → show top results.
It answers "what are the most common items?"
Real Examples
Sort a leaderboard by score (highest first):
sort -k2 -rn scores.txt
Sort /etc/passwd by user ID:
sort -t':' -k3 -n /etc/passwd
Find most frequent log entries:
cat access.log | sort | uniq -c | sort -rn | head -10
Quick Reference
| What you want | Command |
|---------------|---------|
| Alphabetical | sort file |
| Numerical | sort -n file |
| Reverse | sort -r file |
| By column | sort -k2 file |
| Numeric by column | sort -k2 -n file |
| With delimiter | sort -t',' -k2 file |
| Unique only | sort -u file |
Practice
sort is fundamental in CTF challenges for frequency analysis and organizing data for the next step in your pipeline.
sort is the setup for everything else. Once your data is in order, patterns emerge.