Skip to content

Linux Foundations / Find your way around Linux ยท Step 44 of 63

Lesson: uniq (Unique)Switch
โ† Linux Foundations

Shell and files

uniq (Unique)

Learn to remove, count and find repeated lines with uniq.

uniq filters out repeated lines. It is simple, but it has one rule that catches nearly everyone.

Only adjacent lines count

uniq compares each line with the one just before it.

$ cat visits.txt
alice
alice
bob
alice
$ uniq visits.txt
alice
bob
alice

The last alice survives because bob sits between it and the others.

Sort first

Sorting brings equal lines together.

$ sort visits.txt | uniq
alice
bob

If that is all you need, sort -u does it in one step.

Count with -c

-c puts the number of occurrences before each line.

$ sort visits.txt | uniq -c
      3 alice
      1 bob

Add a numeric reverse sort to rank the results, most frequent first:

$ sort visits.txt | uniq -c | sort -nr
      3 alice
      1 bob

This pattern is very useful for logs, such as finding the busiest IP addresses.

Repeated or single lines

-d prints one copy of each line that was repeated. -u prints only lines that were not repeated.

$ sort visits.txt | uniq -d
alice
$ sort visits.txt | uniq -u
bob

Ignore case

-i treats upper and lower case as equal.

$ printf 'Yes\nyes\n' | uniq -i
Yes

The first line of the group is the one printed. When sorting mixed case first, use sort -f so that variants end up next to each other.

Like most filters, uniq writes to stdout. Note that a second file name is treated as the output file and will be overwritten, so uniq a.txt b.txt does not read both.

The streams and text lab lets you try this on real files.

Try it

  1. Run printf 'b\na\nb\nb\n' > v.txt.
  2. Compare uniq v.txt with sort v.txt | uniq.
  3. Count with sort v.txt | uniq -c.
  4. Try -d and -u on the sorted data.

Check your understanding

uniq (Unique)

All 5 sections ยท no timer

Unlimited retries

Questions from every section are combined into one assessment. Answer them all correctly to complete the article.

Your completion saves in this browser. Sign in to sync it to your account.