$_ CLI In Depth
Learning progress 0%
lesson text-processing regex awk

sort & uniq: Counting and Ranking

5 min read Module 6: Text Processing: grep, sed & awk Updated Dec 5, 2026
Cheat Sheet
0:00 / 3:26

sort orders lines

sort reads its input, orders the lines, and writes them out. By default it compares whole lines as text, using the collation rules of the current locale. Options change the comparison. -n compares numeric values, so 10 sorts after 9. -r reverses the order, and -k chooses which field to compare, with -t setting the field separator.

BASH2 lines
printf '0\n9\n100\n'| sort
printf '0\n9\n100\n'| sort -n

The first command prints 10, 100, 9, which is text order. The second prints 9, 10, 100. Forgetting -n on numbers is one of the most common sort mistakes, and the output looks plausible, so check the order when you rely on it.

Sorting by a field

Use -t to name the separator and -k to name the key. The key can be a field number, and it can be followed by n or r to make that key numeric or reversed. A key of -k3,3nr means "field 3 only, numeric, reversed".

BASH1 lines
printf 'ob:3\nann:12\ncy:7\n'| sort -t: -k2,2nr

The output lists ann:12, cy:7, bob:3. This is the core of a ranking. Without -k sort would compare the whole line, and the names would decide the order.

uniq needs sorted input

uniq compares each line with the one before it, and it reports or removes repeats of adjacent lines only. Two equal lines that are separated by a different line are not merged. That is why uniq almost always follows sort. With -c it prints each distinct line preceded by its count, and -d and -u keep only the duplicated or only the unique lines.

BASH2 lines
printf '\na\nb\na\nb\n'| uniq -c
printf '\na\nb\na\nb\n'| sort | uniq -c

The first pipeline prints 1 b, 1 a, 1 b, 1 a, 1 b, because no two equal lines are adjacent. The second sorts first and prints 2 a and 3 b. The count column is padded with spaces, which matters if you later cut it.

Warning

If you forget to sort before uniq -c, the counts look almost right but are wrong. Always put sort in front of uniq unless you have a specific reason not to.

The ranking pipeline

Combine the three steps to count and rank. A common shape is to sort, count with uniq, then sort the counts numerically in reverse and keep the top entries with head. The example ranks the words in a short sentence by frequency.

BASH2 lines
printf 'he cat and the dog and the bird\n'| tr '''
'| sort | uniq -c | sort -rn | head -3

The top line shows 3 the, then 2 and, then one of the single-count words. The first sort groups equal words, uniq counts them, and the second sort ranks by the count column. The tr step in this example turns spaces into newlines, which the next unit explains.

Sorting by several keys

A single sort key is often not enough. A list of files sorted by size, with ties broken by name, needs two keys. You give sort several -k options in order, and each one applies only when the earlier keys are equal. The key syntax is -k start,end, where the end field is optional, and the flags n, r, and h apply to that key only.

BASH1 lines
printf ' 10\na 10\nc 2\n'| sort -k2,2nr -k1,1

The output is a 10, b 10, c 2. The first key ranks by the number in descending order, and the second key, the name, sorts the tied rows in ascending order. Forgetting the second key gives an order that changes from run to run only when the input order changes, which is a subtle bug in reports.

A common mistake is to write -k2nr without an end field. Without a limit, the key runs to the end of the line, so the numeric flag may be applied to the wrong text. Always write both ends of the key, such as -k2,2nr, to name exactly one field.

Sorting also has a cost in time and temporary space. For a file of a few megabytes, the sort is instant. For a file of several gigabytes, GNU sort writes sorted chunks to temporary files and merges them, so a full sort can take minutes and needs free disk space. When you only need the top few values, a full sort is wasteful, and a pipeline that uses sort -rn with head -5 is a reasonable shortcut because sort still reads everything. Measure before you optimize, and keep the pipeline simple.

Stability, uniqueness, and locale

sort -u removes duplicate lines directly, which is shorter than sort followed by uniq when you do not need counts. Note that the notion of equal depends on the sort keys, so sort -u -k1,1 keeps one line per distinct first field. For the output to be the same on every machine, set LC_ALL=C, which sorts by byte value instead of by the collation rules of a language. Locale settings are covered in a later module.

BASH1 lines
printf '\nB\na\n'| LC_ALL=C sort

With the C locale the uppercase B sorts before the lowercase letters, giving B, a, b. Other locales may interleave them. Reproducible sorting is worth setting explicitly in scripts.

Sorting large files

GNU sort uses temporary files when the input does not fit in memory, and -S sets the memory budget. You rarely need to tune it, but it explains why sort is safe on large data: it is designed to merge sorted chunks rather than hold everything in RAM at once.

Terminal lab · 2 steps · real Linux in your browser

Count and rank

Count adjacent duplicates after sorting, then rank scores.

01
Count after sorting
letters.txt has b, a, b, a, b in that order. Sort it first, then count each distinct line: ``bash sort letters.txt | uniq -c > counts.txt ``
Show hint for step 1
uniq needs sorted input, so put sort in front of it.
02
Rank by a numeric field
scores.txt has name:score lines. Sort by the score, highest first, using a colon as the separator: ``bash sort -t: -k2,2nr scores.txt > ranked.txt ``
Show hint for step 2
Name the key with -k2,2, add n for numbers and r for reverse order.
Check yourself Question 1 of 4
Concept Check Numeric comparison in sort recall

Which sort option compares fields as numbers rather than as text?

Recap & Key Takeaways

sort -n compares numbers, sort -t and -k choose a field, and sort -r reverses the order.
uniq only merges adjacent duplicate lines, so sort the input first, and use uniq -c for counts.
A ranking is sort, uniq -c, then sort -rn, with head to keep the top entries.
Set LC_ALL=C in scripts when you need the same sort order on every machine.
Was this lesson helpful? Spot an issue or have a suggestion? Let us know on GitHub.
Report an issue