How do I count the number of lines containing a pattern without making any replacements?
Answer
:%s/pattern//n
Explanation
The n flag in the substitute command suppresses the actual replacement and instead reports the match count. Without the g (global) flag, Vim counts one match per line, giving you the number of lines that contain the pattern — similar to grep -c.
How it works
%— apply to the entire files/pattern//— the substitution (source pattern, empty replacement)n— do not substitute; just report the count
Without g, Vim counts only the first occurrence per line. This means the output tells you how many lines match, not how many total occurrences there are.
For total occurrences across all lines, use gn instead: :%s/pattern//gn
Example
Suppose your file has:
foo bar foo
baz
foo
Running :%s/foo//n reports:
2 matches on 2 lines
Running :%s/foo//gn reports:
3 matches on 2 lines
The first form (without g) counts matching lines; the second counts all occurrences.
Tips
- Combine with a range to count matches in a section:
:10,50s/TODO//n - Use
\cfor case-insensitive counting::%s/\cfoo//n - The
nflag works with any search pattern, including multiline patterns with\n - This is non-destructive: the buffer is never modified