$linuxjunkies
>

uniq(1)

Filter or report on repeated lines in a file or input stream.

UbuntuDebianFedoraArch

Synopsis

uniq [OPTION]... [INPUT [OUTPUT]]

Description

Read lines from INPUT (default: stdin) and write to OUTPUT (default: stdout), either suppressing all but one copy of repeated consecutive lines, or counting and reporting occurrences. The input should typically be sorted first for meaningful results.

uniq compares adjacent lines only; non-consecutive duplicate lines are not treated as repeats. Use sort beforehand to group identical lines together.

Common options

FlagWhat it does
-cPrefix each line with the count of how many times it occurred
-dPrint only duplicate lines (one line per group of duplicates)
-uPrint only unique lines (lines that appear exactly once)
-f NSkip the first N fields when comparing lines
-s NSkip the first N characters when comparing lines
-w NCompare only the first N characters of each line
-iIgnore case differences when comparing lines
-zUse null character as line delimiter instead of newline

Examples

Remove duplicate consecutive lines from a sorted file

sort data.txt | uniq

Count and display each unique line with its occurrence count

sort data.txt | uniq -c

Show only lines that appear more than once in the file

sort data.txt | uniq -d

Display lines that appear exactly once (unique lines only)

sort data.txt | uniq -u

Count occurrences and sort by frequency in descending order

sort data.txt | uniq -c | sort -rn

Skip first 2 fields and compare remaining content for duplicates

uniq -f 2 data.txt

Remove duplicates ignoring case differences

sort names.txt | uniq -i

Related commands