uniq Command in Linux: Filter and Count Duplicate Text Lines
Learn uniq command in linux with syntax, essential flags, practical terminal examples, real-world sysadmin workflows, security tips, and troubleshooting.
9 min read
Learn uniq command in linux with syntax, essential flags, practical terminal examples, real-world sysadmin workflows, security tips, and troubleshooting.
- What uniq Does and When to Use It
- Availability and Installation Across Linux Distributions
- Command Syntax, Arguments, and Exit Status Codes
The uniq command in linux is the standard Unix utility for filtering, reporting, and counting duplicate text records across input streams. Pre-installed as part of GNU coreutils and standardized under POSIX, uniq operates on the principle of adjacent line comparison, scanning records sequentially and collapsing or isolating identical consecutive entries.
The uniq command in Linux filters out or reports adjacent repeated lines from a text file or standard input. Run uniq file.txt to remove adjacent duplicates, uniq -c file.txt to prefix lines with their occurrence counts, or uniq -d file.txt to display only duplicate entries. Input must be sorted first for global deduplication.
A fundamental characteristic of uniq that every systems engineer must understand is that it only evaluates adjacent lines. If identical lines are separated by different content, uniq will not treat them as duplicates. For this reason, uniq is almost universally paired with the sort utility in classic shell pipelines (sort | uniq), creating a powerful data reduction engine.
Beyond basic deduplication, uniq provides specialized reporting options: prefixing lines with precise frequency counts (-c), filtering exclusively for repeated records (-d), filtering exclusively for unique non-repeated records (-u), and ignoring case distinctions (-i). These features make uniq a cornerstone of log analysis, inventory audits, and security telemetry.
What uniq Does and When to Use It
Under the hood, GNU coreutils uniq operates as a lightweight, single-pass streaming filter. Unlike utilities that build full in-memory hash tables or search trees, uniq requires only enough memory to hold two lines in memory simultaneously: the previous line buffer and the current line buffer. As it reads each line from standard input or file descriptor 0, it performs a string comparison against the previous buffer.
If the current line matches the previous line based on the active comparison parameters (respecting field skips via -f, character skips via -s, or character limits via -w), uniq increments an internal duplicate counter. If the line differs, uniq flushes the previous line (and its count, if -c was specified) according to the active filtering mode (-d or -u) and rotates the current line buffer into the previous position. Because its memory footprint is $O(1)$ regardless of dataset size, uniq processes gigabytes of sorted data with near-zero RAM utilization.
Under the hood, uniq gathers runtime telemetry or dispatches control signals by reading virtual filesystems mounted at /proc and /sys, or by communicating with PID 1 (systemd) over D-Bus. Using flags such as -c, -d, -D, -u turns raw process and service tables into actionable diagnostics during incident response.
Availability and Installation Across Linux Distributions
The uniq utility is packaged in coreutils across mainstream Linux distributions. It is pre-installed on standard Ubuntu, Debian, RHEL, Rocky Linux, AlmaLinux, Fedora, and Arch Linux systems, while minimal container images may require manual installation:
Before running administrative tasks or automation scripts, verify whether uniq is installed and inspect which binary path and version your shell resolves:
type -a uniq
uniq --version 2>/dev/null || man -f uniq
# Illustrative output (reviewed against documentation)
uniq is /usr/bin/uniq
uniq (coreutils)
# Debian / Ubuntu
sudo apt-get update && sudo apt-get install -y coreutils
# RHEL / Rocky / AlmaLinux / Fedora
sudo dnf install -y coreutils
# Arch Linux
sudo pacman -S --noconfirm coreutils
# Alpine Linux
sudo apk add --no-cache coreutils
Command Syntax, Arguments, and Exit Status Codes
uniq [OPTION]... [INPUT [OUTPUT]]
The invocation syntax is uniq [OPTION]... [INPUT [OUTPUT]]. If INPUT is omitted or specified as a hyphen (-), uniq reads from standard input. If OUTPUT is omitted, uniq writes results to standard output.
Unlike many GNU tools, uniq allows specifying an optional OUTPUT destination file directly as its second positional argument (e.g. uniq input.txt output.txt), which avoids shell redirection. Options can be combined to refine matching criteria, such as skipping leading fields with -f N or ignoring letter case with -i.
0— Successful execution; input successfully processed and deduplicated.1— Operational failure; unable to read input file or write to output file.2— Command-line syntax error or invalid parameter.
Important Options and Flags Reference
| Option / Flag | Long Form / Argument | Technical Behavior and Purpose |
|---|---|---|
-c | --count | Prefix lines by the number of occurrences. |
-d | --repeated | Only print duplicate lines (lines that occur more than once). |
-D | --all-repeated[=METHOD] | Print all duplicate lines; METHOD can be none, prepend, or separate. |
-u | --unique | Only print unique lines (lines that appear exactly once). |
-i | --ignore-case | Ignore differences in case when comparing. |
-f N | --skip-fields=N | Avoid comparing the first N fields on each line. |
-s N | --skip-chars=N | Avoid comparing the first N characters on each line. |
-w N | --check-chars=N | Compare no more than N characters in lines. |
The -c (--count) option transforms uniq from a simple filter into an aggregation engine. When preceded by sort, sort | uniq -c provides a histogram of unique elements, making it the most popular pipeline idiom for frequency analysis in Linux.
Understanding the contrast between -d and -u is essential: -d emits lines that appear TWO OR MORE times, while -u emits lines that appear EXACTLY ONCE. Combining both flags without understanding their mutual exclusivity will result in no output.
When combining short flags on the command line, POSIX and GNU utilities allow clustering boolean flags behind a single hyphen, provided any option taking an argument appears last. In automated shell scripts, using long-form GNU options where portable makes self-documenting code that is easier to audit during peer review.
Practical Basic and Advanced Usage Examples
1. Remove Adjacent Duplicate Lines from Input
Deduplicate consecutive identical lines in a simple text stream.
cat << 'EOF' > items.txt
apple
apple
banana
orange
orange
orange
EOF
uniq items.txt
# Illustrative output (reviewed against documentation)
apple
banana
orange
uniq merges adjacent duplicates, leaving single occurrences of 'apple', 'banana', and 'orange'.
2. Count Occurrences of Each Line with -c
Display the exact occurrence frequency for each entry in a sorted file.
uniq -c items.txt
# Illustrative output (reviewed against documentation)
2 apple
1 banana
3 orange
The -c flag prefixes each unique line with its count, formatted into a 7-character right-aligned column.
3. Print Only Duplicate Lines with -d
Isolate items that appear multiple times in the dataset while ignoring unique entries.
uniq -d items.txt
# Illustrative output (reviewed against documentation)
apple
orange
The -d flag filters out 'banana' because it appears only once, displaying only repeated entries.
4. Print Only Unique Non-Repeated Lines with -u
Find entries that appear exactly once, filtering out any records that have duplicates.
uniq -u items.txt
# Illustrative output (reviewed against documentation)
banana
The -u flag isolates 'banana' because it is the only record with an occurrence count of 1.
5. Case-Insensitive Deduplication with -i
Deduplicate text while treating lowercase and uppercase letters as identical.
printf "Linux\nlinux\nLINUX\nUbuntu\n" | uniq -i
# Illustrative output (reviewed against documentation)
Linux
Ubuntu
The -i flag normalizes casing, collapsing 'Linux', 'linux', and 'LINUX' into the first encountered instance.
6. Global Deduplication Using sort and uniq Pipeline
Remove duplicate lines from an unsorted file by sorting first.
cat << 'EOF' > unsorted.txt
beta
alpha
gamma
alpha
beta
EOF
sort unsorted.txt | uniq
# Illustrative output (reviewed against documentation)
alpha
beta
gamma
Sorting first brings non-adjacent duplicate 'alpha' and 'beta' entries together so uniq can eliminate them.
Real-World Workflows, Pipelines, and Shell Automation
Security Telemetry: Isolating Top Attacking Subnets
Parse firewall or SSH logs, aggregate attacking IP subnets (/24), and order by attack volume.
#!/usr/bin/env bash
set -euo pipefail
LOG="/var/log/auth.log"
if [ ! -f "$LOG" ]; then LOG="/var/log/secure"; fi
echo "=== Top 5 Attacking Class C Subnets (/24) ==="
grep "Failed password" "$LOG" \
| grep -oE '[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.' \
| sed 's/$/0/24/' \
| sort \
| uniq -c \
| sort -nr \
| head -n 5
# Illustrative output (reviewed against documentation)
=== Top 5 Attacking Class C Subnets (/24) ===
842 198.51.100.0/24
412 203.0.113.0/24
195 192.0.2.0/24
88 198.51.101.0/24
45 203.0.114.0/24
This workflow truncates IPs to subnets, sorts them, aggregates frequencies with uniq -c, and orders by descending threat count.
Database Quality Audit: Finding Duplicate Email Records in CSV
Scan user export CSV files to find duplicate email registrations that violate uniqueness constraints.
#!/usr/bin/env bash
set -euo pipefail
cat << 'EOF' > /tmp/users.csv
1,[email protected]
2,[email protected]
3,[email protected]
4,[email protected]
5,[email protected]
EOF
echo "Auditing /tmp/users.csv for duplicate email addresses..."
cut -d, -f2 /tmp/users.csv \
| sort \
| uniq -cd
# Illustrative output (reviewed against documentation)
Auditing /tmp/users.csv for duplicate email addresses...
2 [email protected]
2 [email protected]
Combining uniq -cd displays both the exact count (-c) and only duplicate records (-d), pinpointing duplicate email records.
Pipelines, Redirection, Quoting, and Shell Expansion
When embedding uniq inside shell pipelines (|), conditional chains (&& and ||), or command substitutions ($(...)), the calling shell performs tilde expansion, variable interpolation, and globbing before invoking the binary. Always wrap paths, patterns, and variables in quotes so whitespace and wildcard characters (*, ?) are not expanded prematurely, and use set -euo pipefail in unattended scripts.
Permissions, Security Implications, and Safe Execution
When specifying an output file (e.g. uniq input.txt input.txt), uniq opens the output file for writing, truncating input.txt to 0 bytes before reading it. Never use the same filename for input and output.
In security auditing, beware of whitespace variations: lines with trailing spaces or tabs (e.g. 'admin' vs 'admin ') will not be recognized as duplicates by uniq. Normalize whitespace using tr or sed before sorting and deduplicating.
Be cautious when relying on uniq -f N (skipping fields) with untrusted user data. If field counts vary across lines, uniq may compare unintended fields, masking duplicate injection attacks.
GNU/Linux, BSD, and BusyBox Implementation Differences
Standard POSIX uniq specifies options -c, -d, -u, -f, and -s. These are universally portable across GNU coreutils, BSD systems (macOS, FreeBSD), and BusyBox on Alpine Linux.
The -D (--all-repeated) option is a GNU coreutils extension and is not supported by standard BSD uniq or BusyBox uniq. For portable scripts needing all duplicate lines, use awk: awk 'seen[$0]++' file.txt.
Troubleshooting Common Errors and Diagnostics
uniq not removing duplicate lines
Root Cause: The input file was not sorted prior to running uniq. uniq only detects adjacent duplicate lines.
Resolution: Sort the file first using sort, or use sort -u.
sort input.txt | uniq
Identical-looking lines not being grouped as duplicates
Root Cause: Lines contain non-visible trailing spaces, carriage returns (\r from Windows), or differing tab characters.
Resolution: Strip carriage returns and trailing whitespace before sorting and deduplicating.
tr -d '\r' < input.txt | sed 's/[[:space:]]*$//' | sort | uniq -c
Input file erased to 0 bytes
Root Cause: The command uniq file.txt file.txt was executed, causing the output argument to truncate the source file.
Resolution: Write output to a separate destination file or use a temporary file.
uniq input.txt output.txt
Alternatives, Related Commands, and Related Tutorials
- Grep Command in Linux: Search Text, Files, and Directories — Practical syntax, flags, and examples for
grep. - awk Command in Linux: Syntax, Text Patterns, and Field Processing — Practical syntax, flags, and examples for
awk. - Cut Command in Linux: Extract Columns, Fields, and Characters — Practical syntax, flags, and examples for
cut. - sort Command in Linux: Sort Lines of Text and Numerical Data — Practical syntax, flags, and examples for
sort. - 25 Best Linux Commands Every Sysadmin Should Know — Core command-line utilities for daily Linux server administration.
- How to Find a File in Linux from the Command Line — Practical file search patterns across Linux directories.
- Linux Commands Knowledge Hub (#linux-commands) — Browse all Linux command-line tutorials and system administration references.
Authoritative References and Official Documentation

The Linux Command Line, 2nd Edition: A Complete Introduction
Frequently Asked Questions
Quick answers to common questions and configurations
Editorial Disclosure: Website Vidya is supported by our readers. When you purchase hosting, tools, or software through our verified partner links, we may earn an affiliate commission at no extra cost to you. We only recommend solutions we trust and rigorously verify.
Rajesh Ray
I’m Rajesh Rai, a full-stack developer, Linux administrator, and technology enthusiast passionate about making complex technology easier to understand and use.
Most Read Guides
TrendingUbuntu Server Not Booting? 10 Simple Steps to Fix It Fast
How to Create a 3D Button in HTML and CSS: Easy Steps
How to Install Python and Pip on Ubuntu 24.04 LTS
How to Install Nginx on Ubuntu 24.04
How to Install Python on Ubuntu 24.04 LTS
Related Technical Guides
Tested runbooks, server administration walkthroughs, and troubleshooting guides



Join the Conversation & Perspective
Have thoughts, counterpoints, or reflections on this story? Engage directly with fellow readers and editorial contributors.
No comments on this guide yet. Be the first to share your thoughts or ask a question!