sort, uniq, and the Counting Pipeline

Two more tools, then a pattern worth memorizing.

sort orders lines alphabetically, or numerically with -n, or backwards with -r.

uniq collapses adjacent duplicate lines, and with -c prefixes each with how many there were.

✦ uniq only sees neighbors

This catches everyone once. uniq compares each line to the one immediately before it, so duplicates scattered through a file are invisible to it. That is why sort almost always comes first: sorting brings identical lines together so uniq can see them. sort | uniq is nearly a single idea, and uniq on its own is usually a bug.

The counting pipeline. This shape answers so many questions that it is worth learning as one unit:

`

sort | uniq -c | sort -rn

`

Sort to group, count the groups, then sort those counts highest first. Feed it a log and it tells you the most common errors. Feed it a list of file extensions and it tells you what a codebase is made of.

SANKOFA SANDBOX
learner:~$

logs/access.log has repeated status codes, which is exactly what this pattern is for.

Try it → Run `cat logs/access.log | sort | uniq -c` and read the counts. Then try it without the sort and see how the result changes, because the duplicates were no longer neighbors.

◈ Graded Task

Answer a question with a pipeline. Work out how many times each distinct line appears in logs/access.log, ordered with the most frequent first, and save the result into summary.txt in your home directory. Do it in a single pipeline without creating any temporary files.

Checked against the filesystem you leave behind, not the commands you type, so any route that gets the job done counts. 4 visible and 3 hidden checks.

SANKOFA SANDBOX
learner:~$

Mark this lesson complete

Signed in, your progress follows you to every device.

Next: Practice Test →
← Back