← Back to Bash Course | Chapter 10: Text Processing Tools | Lesson 9 of 12

wc and uniq

wc counts lines, words, or characters in text, and uniq removes or reports on repeated adjacent lines.

Counting Lines, Words, and Characters

wc reports line, word, and byte counts. Passing -l, -w, or -c restricts the output to just that one count, which is easier to use in scripts than parsing the default three-column output.

Note: Redirecting the file with < instead of passing it as an argument avoids the filename being printed alongside the count.

Example: Counting Lines, Words, and Characters

bash
#!/bin/bash
printf "one two\nthree\n" > sample.txt
echo "lines: $(wc -l < sample.txt)"
echo "words: $(wc -w < sample.txt)"
rm -f sample.txt

Removing Adjacent Duplicates

uniq collapses runs of identical consecutive lines into one. It does NOT remove duplicates scattered non-adjacently through the file, so input is usually sorted first to bring duplicates together.

Example: Removing Adjacent Duplicates

bash
#!/bin/bash
printf "a\na\nb\na\nb\nb\n" > raw.txt
echo "uniq alone (misses non-adjacent duplicates):"
uniq raw.txt
echo "sort then uniq (all duplicates collapsed):"
sort raw.txt | uniq
rm -f raw.txt

Counting Occurrences

uniq -c prefixes each line of output with the number of consecutive times it appeared, turning a list of items into a frequency table.

Example: Counting Occurrences

bash
#!/bin/bash
printf "apple\nbanana\napple\napple\nbanana\n" | sort | uniq -c

Finding the Most Frequent Items

Chaining sort | uniq -c | sort -n sorts items, counts consecutive duplicates, then sorts by that count numerically, producing a ranked frequency list, a very common one-liner.

Example: Finding the Most Frequent Items

bash
#!/bin/bash
printf "a\nb\na\nc\na\nb\n" | sort | uniq -c | sort -n
Common Mistakes
  1. Forgetting uniq only removes ADJACENT duplicate lines, not all duplicates anywhere in the file; the input usually needs to be sorted first.
  2. Using wc -l and forgetting it counts newline characters, so a file missing a trailing newline may report one line fewer than expected.
  3. Not knowing uniq -c prefixes each line with how many times it occurred, which is a very common combination with sort.
Chapter Summary
  • wc -l, wc -w, wc -c count lines, words, and bytes respectively.
  • uniq only collapses consecutive duplicate lines, so input is typically piped through sort first.
  • uniq -c prefixes each output line with a count of how many times it repeated.
  • sort | uniq -c | sort -n is a classic combo for frequency counting.
🔒

Chapter Quiz — Complete all 12 topics to unlock

0/12 topics done

Complete these topics first:

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.