sort reorders the lines of a file. Learn when you need `-n` for numbers, how `-u` drops duplicates, and how `-t` and `-k` pick a column in a CSV, by running the commands in a real terminal in your browser.
Updated: 2026-09-06
sort [options] file...
It prints the lines in order. The file itself is left alone.
$ cat names.txt
grace
ada
linus
ada
margaret
$ sort names.txt
ada
ada
grace
linus
margaret
The default is alphabetical order.
-r reverses it.
$ sort -r names.txt
margaret
linus
grace
ada
ada
Hand sort a file of numbers and the order looks wrong.
$ sort sizes.txt
10
100
2
9
Compared as text one character at a time, 10 really does come before 2.
-n compares them as numbers.
$ sort -n sizes.txt
2
9
10
100
Add -r for largest first.
$ sort -nr sizes.txt
100
10
9
2
-u keeps one copy of each line.
$ sort -u names.txt
ada
grace
linus
margaret
-t sets the separator and -k picks the field.
Ordering a CSV by name, the second column:
$ sort -t, -k2 users.csv
1,ada,web
3,grace,infra
2,linus,infra
id,name,team
The header is just another line to be sorted, which is why it moved to the bottom.
sort is at its best next to uniq -c.
$ cut -d' ' -f1 access.log | sort | uniq -c | sort -nr
3 200
2 404
1 500
Read as three steps it is simple enough.
| Step | What it does |
|---|---|
sort | Puts identical values next to each other |
uniq -c | Counts neighbouring duplicates |
sort -nr | Orders by that count, largest first |
uniq only ever looks at neighbouring lines, so the first sort is not optional.
sort is what you type to see the biggest or most frequent thing first.
| Situation | What to type |
|---|---|
| Count status codes, most common first | cut -d' ' -f1 access.log | sort | uniq -c | sort -nr |
| Get a list with duplicates removed | sort -u emails.txt |
| Order a CSV by one column | sort -t, -k2 users.csv |
| Keep the sorted result | sort names.txt > sorted.txt |
Numbers need -n.
Forget it while sorting file sizes or counts and 100 lands before 9.
The file is not modified.
$ sort names.txt > sorted.txt
$ cat sorted.txt
ada
ada
grace
linus
margaret
Write the output to another file when you want to keep it.
uniq needs a sort in front of it.
uniq compares each line only with the one before it.
Identical lines that are far apart stay separate until you sort them together.
Headers get sorted too.
If the first line of a CSV has to stay put, take it off before handing the rest to sort.
webterm.appthis site
Advanced Terminal Commands
Learn commands for specific situations
learn.webterm.appa separate site

Commands stick when they show up in a real sequence of work, not one at a time. There is a course that builds them up in order.
See the course