Website Vidya
Cloud & DevOpsStep-by-Step Guide

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.

RR
Rajesh RayLead Systems Educator
Published:
9 min read
PDF Cheat Sheet
uniq Command in Linux: Filter and Count Duplicate Text Lines
AI Executive SummaryWebsiteVidya AI

9 min read

Learn uniq command in linux with syntax, essential flags, practical terminal examples, real-world sysadmin workflows, security tips, and troubleshooting.

Key Highlights
  • What uniq Does and When to Use It
  • Availability and Installation Across Linux Distributions
  • Command Syntax, Arguments, and Exit Status Codes
Grounded in full engineering runbookWebsiteVidya AI Engine

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.

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.

Advertisement
uniq Command in Linux: Filter and Count Duplicate Text Lines — syntax, flags, and practical terminal workflow diagram
uniq Command in Linux: Filter and Count Duplicate Text Lines — command syntax, key options, and production workflow reference.

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:

Advertisement

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 / FlagLong Form / ArgumentTechnical Behavior and Purpose
-c--countPrefix lines by the number of occurrences.
-d--repeatedOnly 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--uniqueOnly print unique lines (lines that appear exactly once).
-i--ignore-caseIgnore differences in case when comparing.
-f N--skip-fields=NAvoid comparing the first N fields on each line.
-s N--skip-chars=NAvoid comparing the first N characters on each line.
-w N--check-chars=NCompare 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.

Advertisement

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

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

Authoritative References and Official Documentation

Frequently Asked Questions

Quick answers to common questions and configurations

4 FAQs
uniq operates as a stream filter comparing only the current line to the previous line. To detect duplicates across an entire file without storing everything in memory, identical lines must be grouped contiguously via sort.
Combine the -c and -d options: sort file.txt | uniq -cd. This prints only lines that appear two or more times along with their occurrence count.
Yes. sort -u removes duplicate lines directly within sort, which is faster and consumes fewer process resources. However, if you need occurrence counts (-c) or duplicate isolation (-d), you must use uniq.
Use the -f flag: uniq -f 2 file.txt instructs uniq to skip the first two whitespace-separated fields and compare lines based on remaining columns.
RR
Written byVerified Author

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.

SPAM-FREE MODERATED DISCOURSE

Join the Conversation & Perspective

Have thoughts, counterpoints, or reflections on this story? Engage directly with fellow readers and editorial contributors.

AT
MP
JV
+2

No comments on this guide yet. Be the first to share your thoughts or ask a question!

Recommended Reading10 Guides

Related Technical Guides

Tested runbooks, server administration walkthroughs, and troubleshooting guides

Cloud & DevOps•

How to Close File Descriptors Above 9 in Dash Shell

Attempting to close a file descriptor above 9 in Dash using exec 10<&- results in a 10: not found error because Dash's POSIX lexer only recognizes single-digit file descriptors (0–9) in redirection operators. This guide explains the exact parser limitation, why FDs 10+ are reserved for internal shell state, and how to safely close inherited file descriptors using close_range, Python, or Perl wrappers.

RR
Rajesh Rai
Read More
Featured Infrastructure PartnerUp to 75% OFF + 3 Months Free

Supercharge Your Linux & Cloud Workloads with Hostinger

Deploy high-speed NVMe KVM VPS, Docker containers, and LiteSpeed-accelerated WordPress servers in under 60 seconds with full root access, dedicated IPv4, and 24/7 technical support.

Pure NVMe SSD StorageFull Root Access & SSHFree Domain & Unlimited SSL99.9% Uptime SLA
Plans from$2.99/mo
Claim Hostinger DealAffiliate link • Special discount applied at checkout