FIELD NOTES / UNIX & LINUXNew tools on weekdays. Beyond the man page.
$uniq

uniq: decide what counts as the same observation

Count repeated indicators and reduce noisy records without confusing adjacent runs, whole-file frequency, and evidence you can afford to discard.

THE DEEP DIVE17 MIN READ
01

Collapse a run, not a history

Uniq reads adjacent lines and, by default, prints the first line of each run of equal lines. A run is an uninterrupted sequence: once a different line arrives, the previous run is over. This makes uniq useful for compacting repetitive output, but it does not remember every line it has seen. It is a standalone utility, not a Bash built-in. Give it one filename to read that file; omit the filename to read standard input. Results go to standard output unless you specify an output file.

The distinction matters when reviewing repeated observations. We will start with four synthetic indicator records, then change the ordering, comparison rule, and record delimiter deliberately. The aim is to know exactly what a reduced report still proves.

These examples use Linux, Bash 5.2.21, and GNU Coreutils 9.4. Create a fresh uniq-lab directory; if that name exists, choose another. Mkdir creates it, and cd changes the shell's working directory. Every setup step is joined with &&, which runs the next command only if the previous one succeeds. This prevents a failed directory creation from leaving later writes in the wrong directory. All later examples run inside this lab.

Bash's printf built-in formats text: %s inserts each following argument, and \n ends each record with a newline. The format repeats until all arguments are used. Single quotes protect the enclosed text from shell interpretation. The shell's > creates or replaces the named file. Here the exact input is the four quoted arguments, in their displayed order. Uniq receives indicators.txt as its only operand and does not change it.

TERMINALCOMMAND
mkdir uniq-lab &&
cd uniq-lab &&
printf '%s\n' 'fail.example' 'fail.example' 'ok.example' 'fail.example' > indicators.txt &&
uniq indicators.txt
TERMINALEXPECTED OUTPUT
fail.example
ok.example
fail.example

The first two records become one, but the final fail.example remains because ok.example broke the run. This is correct output, not a failure to find a duplicate. Sorting is optional when the question is about consecutive repetition.

02

Count runs, then choose which runs to keep

The -c flag prefixes each representative with its run length. It includes the first occurrence: two identical adjacent lines produce a count of 2, not 1. The -d flag prints one representative only for runs of at least two lines. The -u flag does the opposite: it prints only runs of exactly one line. Neither selector means “search the whole file for this value.”

The following commands reuse the unchanged fixture. Printf adds headings so the three results are distinguishable. GNU uniq pads the displayed counts with spaces; do not make a parser depend on that cosmetic width.

TERMINALCOMMAND
printf '%s\n' 'counts:'
uniq -c indicators.txt
printf '%s\n' 'repeated runs:'
uniq -d indicators.txt
printf '%s\n' 'singleton runs:'
uniq -u indicators.txt
TERMINALEXPECTED OUTPUT
counts:
      2 fail.example
      1 ok.example
      1 fail.example
repeated runs:
fail.example
singleton runs:
ok.example
fail.example

The final fail.example is a singleton run even though the same text appeared twice earlier. In particular, -u is not the usual “deduplicate this list” operation: it removes repeated runs altogether.

03

Make whole-file frequency a deliberate change

To count a value across the entire supplied file, first bring equal values together. Sort orders whole lines by default; the shell's | sends its standard output to uniq's standard input. This changes chronology into grouping. The sort deep dive explains comparison keys and tie handling; the essential refresher is that sorting controls adjacency, while uniq decides what to do with each resulting run.

LC_ALL=C is a command-local environment assignment selecting the C locale, which gives these ASCII records predictable byte ordering. A locale supplies character and comparison rules. The assignment appears on both commands because an assignment on one side of a pipe does not configure the command on the other side. None of these pipelines modifies indicators.txt.

TERMINALCOMMAND
printf '%s\n' 'whole-file counts:'
LC_ALL=C sort indicators.txt | LC_ALL=C uniq -c
printf '%s\n' 'repeated values:'
LC_ALL=C sort indicators.txt | LC_ALL=C uniq -d
printf '%s\n' 'values seen once:'
LC_ALL=C sort indicators.txt | LC_ALL=C uniq -u
TERMINALEXPECTED OUTPUT
whole-file counts:
      3 fail.example
      1 ok.example
repeated values:
fail.example
values seen once:
ok.example

These are frequencies in this file, not necessarily counts of independent events. A collector can repeat one observation. Plain sort followed by plain uniq is a useful whole-line reduction; do not assume it is interchangeable with every form of sort's -u flag, which suppresses values equal under sort's comparison rule. POSIX specifically distinguishes identical lines from nonidentical lines that a locale may collate equally. With selected sort keys, equality can also be narrower than the whole line. Pin the locale and state the comparison rule instead of calling the result simply “unique.”

04

Match case handling at both stages

Suppose a supplied identifier list treats ASCII letter case as irrelevant. GNU uniq's -i flag ignores case during comparisons; it does not change the spelling printed. Ordinary C-locale sort places uppercase letters before lowercase letters, so an unrelated value can still separate two case variants. The first pipeline below therefore fails to bring equivalent values together.

Sort's -f flag folds letter case for ordering. The second pipeline uses that ordering with uniq -i, so both stages agree about the intended grouping. This block creates case.txt in the lab, replacing it if you repeat the block. The fixture contains AA, BB, and aa, in that order.

TERMINALCOMMAND
printf '%s\n' AA BB aa > case.txt &&
printf '%s\n' 'ordinary ordering:' &&
LC_ALL=C sort case.txt | LC_ALL=C uniq -i
printf '%s\n' 'case-folded ordering:'
LC_ALL=C sort -f case.txt | LC_ALL=C uniq -i
TERMINALEXPECTED OUTPUT
ordinary ordering:
AA
BB
aa
case-folded ordering:
AA
BB

AA is the first representative delivered by this sort; it is not a canonical spelling established by uniq. This example makes only an ASCII, C-locale claim. Case folding is not Unicode normalization, and an application's identifier rules may differ from the locale's character rules. Do not apply it to case-sensitive usernames, tokens, or paths just because the report becomes shorter.

05

Ignore one field without inventing a log parser

Repeated messages often carry different timestamps. The -f option takes the number of initial fields to skip when comparing. In -f 1, the argument 1 skips just the first field. A field consists of any leading blanks followed by nonblank characters; under the C locale, blanks here are spaces or tabs. The blanks before the next field remain in the comparison. This is not a timestamp parser, and it is not a delimiter-aware CSV parser.

Create events.txt with the four exact records below. The trailing backslash continues the printf command onto the next physical line; it must be the last character on that line. The comparison suffix for the first two records is the same: one space followed by DENY user=alex. The -c flag counts matching suffixes, but uniq still prints the entire first record, including its original timestamp.

TERMINALCOMMAND
printf '%s\n' \
  '10:00:00 DENY user=alex' \
  '10:00:01 DENY user=alex' \
  '10:00:02 ALLOW user=alex' \
  '10:00:03 DENY user=alex' > events.txt &&
LC_ALL=C uniq -c -f 1 events.txt
TERMINALEXPECTED OUTPUT
      2 10:00:00 DENY user=alex
      1 10:00:02 ALLOW user=alex
      1 10:00:03 DENY user=alex

The count beside 10:00:00 summarizes a run beginning there; it does not mean both events occurred at that exact timestamp. This can reduce a noisy view during an authorized review of supplied authentication records. Keep the original evidence: the reduced view loses the second timestamp, and matching message text does not establish identical underlying activity.

06

Separator spacing can break the intended group

The field definition has an easy-to-miss consequence. Skipping the first field in '01 DENY' leaves one leading space, while skipping it in '02 DENY' leaves two. Uniq does not automatically trim the comparison suffix. This supplementary input is supplied directly by printf, with two spaces in its second argument.

TERMINALCOMMAND
printf '%s\n' '01 DENY' '02  DENY' | LC_ALL=C uniq -c -f 1
TERMINALEXPECTED OUTPUT
      1 01 DENY
      1 02  DENY

If an application's schema says those two records should be equivalent, normalize or parse them explicitly in a separate, documented step. Whitespace can also be meaningful evidence, so do not silently erase it while claiming an exact comparison.

07

Compare a window, preserve a representative

For a fixed-width ASCII format, -s takes a count of initial characters to skip. GNU -w takes the maximum number of remaining characters to compare. These options change comparison, not output extraction. The rows below make the window visible before we use it: in '01:AUTH allow', skipping three characters leaves 'AUTH allow'; checking four of those characters compares only 'AUTH'. In '03:DISK full', the corresponding pieces are 'DISK full' and 'DISK'.

The block creates classes.txt. First, -s 3 compares the full suffix; AUTH allow and AUTH deny remain different. Then adding -w 4 deliberately groups those adjacent records by their four-character category. If -f and -s are combined, fields are skipped first, then characters; -w limits the comparison after both skips. These fixtures are ASCII in the C locale, where each character is one byte. The GNU 9.4 implementation uses byte offsets for these windows, despite the options' character-oriented names; do not assume they count complete multibyte characters. Other implementations need their own check.

TERMINALCOMMAND
printf '%s\n' '01:AUTH allow' '02:AUTH deny' '03:DISK full' > classes.txt &&
printf '%s\n' 'full suffix:' &&
LC_ALL=C uniq -c -s 3 classes.txt
printf '%s\n' 'four-character category:'
LC_ALL=C uniq -c -s 3 -w 4 classes.txt
TERMINALEXPECTED OUTPUT
full suffix:
      1 01:AUTH allow
      1 02:AUTH deny
      1 03:DISK full
four-character category:
      2 01:AUTH allow
      1 03:DISK full

The second result must not be read as two allows. It means two adjacent AUTH-category records, represented by the first full line. A projection can hide the very difference an investigation needs. Use such a view only with a label that describes the comparison window, and retain the original records.

08

An empty comparison key can collapse unrelated records

If -s skips beyond the end of a line, the comparison uses an empty string. The same empty-key outcome applies when -f skips more fields than a record has. Adjacent short or malformed records can therefore become one group even though their original bytes differ.

Here both input records have only one character. Skipping five leaves nothing to compare in either record. Nothing is written to disk.

TERMINALCOMMAND
printf '%s\n' a b | LC_ALL=C uniq -c -s 5
TERMINALEXPECTED OUTPUT
      2 a

This is why validating the input shape belongs before a fixed-position reduction. The output is a valid summary under the requested rule and a misleading summary if you mistake that rule for full-record equality.

09

Empty lines and invisible differences are still records

An empty line is not ignored. Two adjacent empty lines collapse to one; a line containing a space is different from an empty line, and a tab differs from a space. Trailing spaces are significant too. The format string below supplies two empty lines, two one-space lines, a one-tab line, x followed by a space, and finally x alone. Printf interprets \t as a tab.

To make those differences visible, od displays output bytes in hexadecimal. Its -A n option suppresses address labels, -t x1 selects one-byte hexadecimal units, and -v prevents repeated rows from being abbreviated. In this display, 0a is newline, 20 is space, 09 is tab, and 78 is x.

TERMINALCOMMAND
printf '\n\n \n \n\t\nx \nx\n' | LC_ALL=C uniq | od -A n -t x1 -v
TERMINALEXPECTED OUTPUT
 0a 20 0a 09 0a 78 20 0a 78 0a

Read the bytes as five output records: empty, space, tab, x-space, and x. A terminal display that makes two lines look alike is not evidence that their bytes match. Likewise, a carriage return from a different line-ending convention remains data, not an automatic invitation for uniq to normalize it.

10

Keep an embedded newline inside its record

Newline-delimited text is the wrong transport when one record can contain a newline. GNU uniq's -z flag uses NUL, the zero byte, as both input and output record terminator. GNU sort -z uses the same convention. All stages must agree: changing only uniq would not repair records already split by a newline-oriented producer or sorter.

This fixture represents three synthetic path strings: a-newline-b twice, followed by c. Printf's \000 escape writes a NUL byte, while \n remains an embedded newline. The first pipeline collapses the adjacent pair. The second also sorts the records before reducing them. Neither command creates or opens the represented paths. Od makes the separators visible: 00 ends a record; the 0a inside the first record stays inside it.

TERMINALCOMMAND
printf 'a\nb\000a\nb\000c\000' | LC_ALL=C uniq -z | od -A n -t x1 -v
printf 'c\000a\nb\000a\nb\000' | LC_ALL=C sort -z | LC_ALL=C uniq -z | od -A n -t x1 -v
TERMINALEXPECTED OUTPUT
 61 0a 62 00 63 00
 61 0a 62 00 63 00

This is record framing, not filename validation or permission checking. Do not convert a NUL stream back to newline text before a consumer that needs unambiguous paths. Avoid storing it in a Bash variable, which cannot preserve embedded NUL bytes. The C locale also avoids assuming that arbitrary pathname bytes are valid text in some other encoding.

11

Streaming is not a promise of immediate output

Uniq needs information about the current run, not a table of every previously seen value. That makes it useful on an already grouped stream without a whole-input sort. But a count is final only when a different comparison value or end-of-input closes the run. A singleton decision also needs that boundary. A second matching record establishes repetition, but the GNU 9.4 implementation's -d path still waits until the run ends before writing its representative. An indefinitely open run has no final count yet.

Default GNU uniq can select a run's first representative without waiting for its final size. That is not an end-to-end latency guarantee. Producers, uniq's standard-output buffering, and downstream programs can delay visible output. Ordinary sorting is a different constraint: it needs the complete input to establish global order. Putting sort before uniq turns a live-stream reduction into a whole-input operation.

If an operational dashboard needs bounded windows, explicit flush behavior, or counts every minute, define those requirements outside uniq. An adjacent-run reducer does not acquire a clock, durable state, or delivery guarantees merely because it is placed in a pipeline.

12

Success does not mean a duplicate was found

Uniq returns zero on successful completion, even when -d prints nothing. A nonzero status indicates an error, not “no repeated records.” This differs from search tools whose statuses encode whether a match exists. In Bash, $? expands to the preceding command's exit status; save it immediately with status=$? before another command replaces it. Double quotes around "$status" pass that expanded value as one argument to printf.

The first pipeline contains only singleton runs and therefore prints no data. Its status is zero. The second command reads absent.txt, a name not created by these fixtures. The shell's 2> sends standard error to missing.err, creating or replacing that diagnostic file inside the lab. The example displays the saved status and uses cat to print the retained diagnostic. It does not hide failure behind an empty data stream.

TERMINALCOMMAND
printf '%s\n' alpha beta | LC_ALL=C uniq -d
status=$?
printf 'no-repeat status=%s\n' "$status"
LC_ALL=C uniq absent.txt 2> missing.err
status=$?
printf 'missing-input status=%s\n' "$status"
cat missing.err
TERMINALEXPECTED OUTPUT
no-repeat status=0
missing-input status=1
uniq: absent.txt: No such file or directory

The exact error text and nonzero value shown are from GNU 9.4 under the C locale; portable code tests zero versus nonzero. Bash normally reports only the last command's status for a pipeline. Its pipefail shell option instead reports a nonzero pipeline status when an earlier stage fails, so production processing must account for producer and sort failures as well as uniq's status. Still keep diagnostics: successful completion is not proof of input completeness.

13

Keep the conclusion as narrow as the comparison

Use a sorted count of supplied indicators to choose what to inspect next. Use a run count to see bursts in an existing sequence. Use a projected comparison to reduce a labeled view when the ignored information is genuinely irrelevant. These are different questions, and all can be useful during routine administration or an authorized assessment. A repeated hostname is not proof of compromise; a missing row in a reduced view is not proof that the original record never existed.

Retain the source artifact, its provenance, the exact comparison command, the locale, and the implementation version. Never redirect output onto the input file: shell redirection can truncate it before uniq reads it. Even the utility's separate output-file operand is not a safe in-place editing contract. Use a distinct output path if you need a saved view.

POSIX.1-2024 specifies the -c, -d, -u, -f, and -s options used here for text input. The -i, -w, and -z behaviors are GNU extensions in this walkthrough, not promises made by POSIX. Other implementations may provide them: the uutils documentation lists these options, but that listing is not a test of parity for locale, multibyte text, diagnostics, or buffering. Check the installed implementation before carrying a sensitive evidence-processing recipe between systems.

Back to latest issue
HELP SHAPE THE NEXT ISSUE

What belongs in your toolbox?

Choose a command you want to know better. We start with familiar tools and work toward the less obvious ones.

READER’S CHOICE

What should we cover next?

Vote for a future deep dive, or suggest a command we missed.

One command name, up to 32 characters. Suggestions are reviewed by a person. A new article starts a fresh poll.

Loading poll…