← Back to Bash Course | Chapter 11: Process Management | Lesson 9 of 12

uniq

uniq is like a teacher who crosses out repeated names sitting side by side on a list. It only spots repeats that are next to each other, so you sort first.

In this page:

  1. uniq
Syntax
bash
sort file_name | uniq [-c]

uniq

uniq removes consecutive duplicate lines from sorted input, so it's almost always used after sort in a pipeline. -c prefixes each line with a count of how many times it occurred.

Without sorting first, uniq will miss duplicates that aren't adjacent.

Warning: uniq only removes *adjacent* duplicate lines — always sort first if duplicates might not be next to each other.

Example: uniq

bash
#!/bin/bash
printf "apple\nbanana\napple\napple\ncherry\n" | sort | uniq
echo "---"
printf "apple\nbanana\napple\napple\ncherry\n" | sort | uniq -c
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Using uniq without sort, since it only removes adjacent duplicates.
  2. Forgetting -c when you want counts.
  3. Expecting uniq to ignore case without -i.

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.