Bash uniq Command - Remove Duplicate Lines
Using the uniq Command
The uniq command removes repeated lines, so each line is shown only once.
The examples below use this file, fruits.txt:
apple
banana
apple
cherry
banana
apple
uniq Needs Sorted Input
uniq only removes duplicates that are next to each other. In fruits.txt, no line is followed by the same line, so nothing is removed:
Example: uniq on an Unsorted File
uniq fruits.txt
apple
banana
apple
cherry
banana
apple
Sort the lines first, so the same lines end up next to each other:
sort -u gives the same result in one command. Use uniq when you need its options, like counting.
Count Each Line (-c)
Use -c to show how many times each line appears:
Show Only Duplicates (-d)
Use -d to show only lines that appear more than once:
Show Only Unique Lines (-u)
Use -u to show only lines that appear exactly once:
Ignore Case (-i)
Use -i to treat upper and lower case as the same, so "Apple" and "apple" count as duplicates:
Options Overview
-c: Count how many times each line appears-d: Show only repeated lines-u: Show only lines that are not repeated-i: Ignore upper and lower case