🎓 A1Learner
🔍
0 of 50 lessons completed

Unique Lines

uniq drops lines that repeat. A repeat is a line that matches the line above it.

uniq alone changes nothing

names.txt has no repeats side by side. uniq prints every line as it is.

$ cd ~/practice
$ uniq data/names.txt

Count each name

sort puts the same names side by side. uniq -c counts each name.

$ cd ~/practice
$ sort data/names.txt | uniq -c

Each name once

sort and uniq together print each name once.

$ cd ~/practice
$ sort data/names.txt | uniq

Example

$ cd ~/practice
$ sort data/numbers.txt | uniq -c

Key points

  • Use uniq to drop lines that repeat.
  • uniq drops a line only when the same line sits right above it.
  • Use uniq -c to count how many times each line repeats.
  • uniq -c prints a count in front of each line.
  • Sort the lines first, so repeats sit side by side.
  • uniq never changes the file. It only prints the lines that stay.

In this example, sort puts the numbers in order. uniq -c counts each number. 1 appears once, 3 appears twice, 5 appears twice, and 8 appears once.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

Why does uniq need sorted lines first?