Skip to the workspace
Pebellslearn by building
Text Processing  ›  Lesson

sort, uniq and tr — Ordering, Counting and Changing Characters

sort 15 minsort orders lines, uniq merges only adjacent duplicates so it follows sort, uniq -c counts them, and tr translates, squeezes or deletes characters from stdin.

linux / sort, uniq and tr — Ordering, Counting and Changing Characters

Explore each scene at your own pace.

01 · The rule

The rule

sort, uniq and tr — Ordering, Counting and Changing Characters

"Which crop did we pick most often?" is one of the most common questions you can ask about data. It turns out to be a single line of shell: slice out a column, put it in order, count the repeats, and put the counts in order. tr joins them as a tool for tidying text one character at a time.

The rule

sort before uniq, always.

sort puts lines in order. By default it sorts alphabetically, and a few options change that:

Option Does
-n numeric order, so 10 comes after 9
-r reverse the order
-t, fields are separated by commas
-k3 sort starting from field 3
-u keep only one of each identical line
$ tail -n +2 harvest.csv | sort -t, -k3 -n | head -n 1
2026-06-01,basil,0.4,ravi

That line finds the smallest pick: skip the header, sort by kilograms numerically, and keep the first line.

uniq removes duplicate lines, but only when they are next to each other. That's why it nearly always comes after sort. uniq -c puts a count in front of each line:

$ tail -n +2 harvest.csv | cut -d, -f2 | sort | uniq -c
      2 basil
      1 chilli
      3 tomato

tr (translate) changes or deletes characters. It only reads stdin, so you feed it through a pipe or with <:

$ echo tomato | tr a-z A-Z          # TOMATO
$ echo "kg   3.5" | tr -s ' '       # squeeze repeated spaces: kg 3.5
$ tr -d '\r' < windows.csv > unix.csv   # delete Windows carriage returns
$ tr ',' '\t' < harvest.csv         # commas become tabs

Two tab-tidying cousins: expand turns tabs into spaces, and unexpand turns runs of spaces back into tabs.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.