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
aliceThe last alice survives because bob sits between it and the others.
Sort first
Sorting brings equal lines together.
$ sort visits.txt | uniq
alice
bobIf 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 bobAdd a numeric reverse sort to rank the results, most frequent first:
$ sort visits.txt | uniq -c | sort -nr
3 alice
1 bobThis 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
bobIgnore case
-i treats upper and lower case as equal.
$ printf 'Yes\nyes\n' | uniq -i
YesThe 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
- Run
printf 'b\na\nb\nb\n' > v.txt. - Compare
uniq v.txtwithsort v.txt | uniq. - Count with
sort v.txt | uniq -c. - Try
-dand-uon 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.