Skip to main content

uniq Cheatsheet

By Dejan Panovski Updated on Download PDF

Quick reference for filtering and counting duplicate lines with uniq in Linux

The `uniq` command filters or reports repeated adjacent lines from a file or standard input. This cheatsheet covers counting duplicates, showing only unique or repeated lines, case-insensitive matching, and the common `sort | uniq` pipelines.

Basic Syntax

Core uniq command forms.

CommandDescription
uniq file.txtRemove adjacent duplicate lines
uniq input.txt output.txtWrite filtered result to a file
sort file.txt | uniqSort first so all duplicates are adjacent
cat file.txt | uniqRead from standard input
uniq -z file.txtUse NUL as the line delimiter

Count and Filter

Count occurrences or isolate duplicate and unique lines.

CommandDescription
uniq -c file.txtPrefix each line with its occurrence count
uniq -d file.txtPrint only duplicated lines, one per group
uniq -D file.txtPrint every line of each duplicate group
uniq -u file.txtPrint lines without an adjacent duplicate
sort file.txt | uniq -c | sort -rnFrequency count, most common first

Comparison Control

Change which part of each line is compared.

CommandDescription
uniq -i file.txtIgnore case when comparing
uniq -f1 file.txtSkip the first field before comparing
uniq -s5 file.txtSkip the first 5 characters
uniq -w10 file.txtCompare only the first 10 characters
uniq --group file.txtShow all lines, groups split by a blank line

Common Pipelines

Practical combinations with other commands.

CommandDescription
sort access.log | uniq -c | sort -rn | headMost frequent log lines
cut -d, -f1 data.csv | sort | uniqUnique values from a CSV column
awk '{print $1}' access.log | sort | uniq -cCount requests per IP address
sort emails.txt | uniq -dAddresses that appear more than once
sort words.txt | uniq -uWords that appear exactly once

Troubleshooting

Quick checks for common uniq issues.

IssueCheck
Duplicates not removedLines must be adjacent; pipe through sort first
Case treated as differentAdd -i to ignore case
Trailing spaces split groupsNormalize whitespace first (e.g. sed 's/ *$//')
Fields skipped incorrectly-f skips whitespace-separated fields, not delimiter columns
Count column hard to rankPipe uniq -c into sort -rn to order by frequency

Use these guides for full duplicate-handling and text-processing workflows.

GuideDescription
uniq Command in LinuxFull uniq guide with examples
sort Command in LinuxSort lines so duplicates become adjacent
sort CheatsheetQuick reference for sorting options
wc Command in LinuxCount lines, words, and bytes
cut Command in LinuxExtract fields from text
awk Command in LinuxField-based text processing