Amazon holiday deals See deals →ad

Mets Minor League Blog

Music theory, instruments and musicians

Mets Minor League Blog

Music theory, instruments and musicians

Linux grep Unique Values: Commands and Examples

grep finds lines that match a pattern, but it does not remove duplicates or calculate unique values by itself. On Linux, pipe its matching output to sort -u for distinct lines, or use tools such as awk when you need unique fields or want to keep the original order.

What “unique values” means

The right command depends on what you mean by a value. A text file contains lines, and the simplest interpretation is that each complete line is a value. In other cases, you may want distinct usernames in a particular column, individual words that match a pattern, or only the first occurrence of each result. These are different tasks, so there is no single “unique” option for grep.

For example, a log might contain several lines mentioning the same address. You could want each distinct matching line, or you could want each distinct address regardless of the rest of the line. The first task is a line-deduplication problem. The second requires extracting the address before deduplicating it. Choosing the output you want first prevents a common mistake: removing duplicate lines and assuming that this also makes a field within those lines unique.

Also distinguish “unique” from “appears exactly once.” In everyday command-line usage, “unique values” often means one copy of every different value. By contrast, a value that appears exactly once is a non-repeated value. The commands below show how to produce distinct results; a later example covers finding values that occur only once.

Get distinct matching lines with grep and sort

For one copy of every distinct line that matches a pattern, use a pipeline:

grep 'ERROR' app.log | sort -u

grep prints matching lines, and sort -u sorts those lines while suppressing duplicates. The comparison is made on the complete line, not just on the text that matched. Given these lines:

ERROR disk full
INFO retrying
ERROR disk full
ERROR network down

the command returns the two different error lines. The repeated ERROR disk full line appears once. The nonmatching informational line is excluded before sorting.

You can use grep’s usual pattern options in the first part of the pipeline. For example, grep -i 'error' app.log | sort -u matches “error” without regard to case, while grep -E 'error|warning' app.log | sort -u uses extended regular expressions to match either word. These options affect which lines grep selects; the final command still deduplicates whole output lines.

Extract matching text before deduplicating

If you want unique matches rather than unique lines, extract the matching portion and then sort it. GNU grep, commonly installed on Linux systems, provides -o to print each nonempty matching part on its own line:

grep -Eo '[[:alnum:]._%+-]+@[[:alnum:].-]+' contacts.txt | sort -u

This example prints email-like strings found by the pattern and returns one copy of each distinct result. It is useful for simple text extraction, but the expression is not a complete validator for every possible email address. More generally, grep -o reports matched portions, not semantic fields: if a line has multiple matches, it can print multiple output lines.

To extract unique numbers, for example, you might use grep -Eo '[0-9]+' data.txt | sort -u. To extract words beginning with “cat,” use grep -Eo '\bcat[[:alpha:]]*\b' notes.txt | sort -u where the grep implementation supports the word-boundary syntax used. For more portable character matching, prefer POSIX character classes such as [[:alpha:]] over assumptions about ASCII ranges. GNU grep’s -o is widely available on Linux, but it is not part of the POSIX specification for grep, so scripts intended for varied Unix systems should check their target implementation.

Deduplicate a particular column or field

When the value is one field in a record, extract that field before sorting. For a whitespace-separated file where the username is the second field, for example:

grep 'enabled' users.txt | awk '{print $2}' | sort -u

Here grep filters records first, awk prints field two, and sort -u returns distinct field values. The order matters: sorting whole records before extracting a field would not necessarily make repeated usernames adjacent in the way a later uniq command requires. With sort -u after extraction, each value is compared directly.

Awk splits input into fields on runs of whitespace by default. That makes the example suitable for ordinary space- or tab-delimited text, but not necessarily for CSV, where quoted commas and embedded line breaks require a CSV-aware parser. For a tab-separated file, you can set the field separator explicitly, such as awk -F '\t' '{print $2}'. Confirm the file’s actual delimiter and field numbering before using a field-based pipeline.

Keep the first-seen order instead of sorting

sort -u is concise and works well when sorted output is acceptable. It changes the order, though. If the output must follow the order in which values first appeared, use an awk seen-set:

grep 'ERROR' app.log | awk '!seen[$0]++'

Awk evaluates each line as an array key. The first time a line appears, its counter is initially zero, so the condition succeeds and the line is printed. Later occurrences increment the counter but are not printed. The result keeps the first occurrence of each complete matching line.

For a field, print and track the field rather than the whole record. For example, awk '{if (!seen[$2]++) print $2}' outputs each second-field value once, in first-seen order. If you want to retain the first complete record for every distinct second field, use awk '!seen[$2]++' instead. This distinction—printing the key versus printing the original record—is useful when deduplicating data without losing its associated columns.

Case, sorting, and locale

Text comparison can be affected by case and locale. By default, sort -u treats strings that differ in capitalization as distinct on typical Linux setups, so alice and Alice may both appear. If you want case-insensitive sorting and deduplication, use sort -fu. The output keeps a representative spelling; do not rely on a particular capitalization being selected when values compare equal under the chosen rules.

Similarly, grep -i makes pattern matching case-insensitive, but it does not normalize the printed lines. Thus grep -i 'error' log.txt | sort -u can still emit both Error found and ERROR found, because grep passes through their original text and the sort step sees different spellings. Choose case-insensitive behavior at the deduplication step as well when that is the intended definition of “same.”

Locale settings can influence how text is ordered and compared. For reproducible byte-oriented sorting in scripts, people often set LC_ALL=C, for example LC_ALL=C sort -u. This can be appropriate for machine-generated identifiers, but it may not match the language-aware ordering users expect for natural-language text. Set the locale deliberately rather than assuming that every machine will sort all characters identically.

Common mistakes and practical limits

  • Expecting grep to deduplicate. Grep selects matching lines; repeated input lines remain repeated unless a later command removes them.
  • Using uniq on unsorted output. uniq only collapses adjacent repeated lines. Use sort | uniq or the shorter sort -u when global deduplication is wanted.
  • Deduplicating the wrong thing. grep pattern file | sort -u compares entire lines. Extract a field or match first if that is the value that should be distinct.
  • Assuming sorted output preserves input order. It does not. Use an order-preserving seen-set such as Awk’s array pattern when first-seen order matters.
  • Ignoring pipeline failures. In a simple shell pipeline, the status may reflect only the final command. In Bash, set -o pipefail makes a pipeline fail if an earlier command fails, which can matter in scripts.

For very large input, sorting may use temporary disk space as well as memory, depending on the data size and system settings. GNU sort can use a temporary directory configured with its options or environment, and its documentation describes memory and temporary-file controls. An Awk seen-set avoids sorting and preserves order, but it must retain distinct keys in memory. Choose based on data size, available resources, and whether output order matters.

When to use sort, uniq, or awk

Use sort -u when you want a straightforward list of distinct lines or extracted values and alphabetical or locale-based ordering is fine. Use sort | uniq if you also need uniq features such as counting adjacent occurrences with uniq -c; sorting first ensures equal values are together. Use Awk when you need original order, custom field selection, or a small amount of per-value logic.

If you need counts rather than just distinct values, a useful pattern is grep 'ERROR' app.log | sort | uniq -c. It produces a count for each matching line, with the values sorted. For distinct extracted matches with counts, use grep -Eo 'pattern' file | sort | uniq -c, replacing pattern with an appropriate expression. Counts are counts of the exact output strings unless you deliberately normalize case or otherwise transform the data first.

To find values that occur exactly once—not one copy of every distinct value—count them and filter the counts. For instance, grep -Eo '[0-9]+' data.txt | sort | uniq -c | awk '$1 == 1 {print $2}' prints numbers appearing once. This assumes each extracted number is on its own line and that the count and value occupy the first and second fields in uniq -c output. That is a different result from ordinary deduplication, which keeps values that may have appeared many times.

Frequently Asked Questions

Can grep show each matching line only once?
Not by itself. Pipe its results to sort -u to remove duplicate complete lines, or use awk '!seen[$0]++' if you need to preserve first-seen order.

How do I get unique words from a file with grep?
On GNU grep, extract matches with grep -Eo 'your-pattern' file and pipe them to sort -u. Use a pattern that matches the whole word or token you want; otherwise, partial matches may be returned.

What is the difference between sort -u and uniq?
sort -u sorts and removes duplicates across the input. uniq only removes repeated adjacent lines, so unsorted duplicates can remain. The common alternative is sort | uniq.

How can I keep the original order?
Use awk '!seen[$0]++' after grep to print the first occurrence of each complete line. For a particular field, use that field as the array key, such as awk '!seen[$2]++'.

How do I ignore capitalization when finding unique values?
For sorting and deduplication, use sort -fu. Grep’s -i changes which lines match, but does not make differently capitalized output lines identical to a later ordinary sort -u.

Linux grep Unique Values: Commands and Examples
Scroll to top