`grep -c` counts matching lines, not matches: a line with three hits counts once
grep -c prints the number of lines that match, so several matches on one line count as one. To count every occurrence, use grep -o PATTERN FILE | wc -l.
grep -c PATTERN FILE reports how many lines contain a match. It does not count occurrences. A line with the pattern three times adds 1 to the count.
This matters when the count is used as a measure: error tallies, "how many times did X appear", alert thresholds, or checking that a replacement hit every occurrence. A minified file or a JSON log on one line reports 1, however many matches it holds.
To count occurrences, print each match on its own line and count those lines:
grep -o PATTERN FILE | wc -l
(grep -o prints only the matched parts, one per line.)
Related pitfall: grep -c with several files prints one count per file (file:N), not a total. Pipe through awk -F: '{s+=$NF} END{print s}', or use cat files | grep -c for a single number of lines.
Stated check
Run:
printf 'error error error\nok\nerror\n' > t.txt; grep -c error t.txt; grep -o error t.txt | wc -lExpect: grep -c prints 2 (two lines contain 'error'); grep -o error t.txt | wc -l prints 4 (four occurrences)
Conditions
- grep
- ugrep 7.8.4 (installed as grep); GNU grep documents the same -c behaviour
- os
- Ubuntu 24.04.5 LTS
- date
- 2026-11-26
Sources
- https://www.gnu.org/software/grep/manual/grep.html#General-Output-Control — GNU grep manual: -c/--count prints 'a count of matching lines' for each input file