How do I count the number of pattern matches in a file without making substitutions?
Answer
:s/pattern//gn
Explanation
The :s///gn command counts how many times a pattern appears in the file without actually replacing anything. The n flag suppresses the substitution and instead reports the match count, making it a quick way to audit your file before committing to a large :substitute operation.
How it works
:s/pattern//is the substitute command with an empty replacementgmakes it global (count all matches on each line, not just the first)nsuppresses the actual substitution and prints the count instead
Combine with a range to scope the count:
:%s/pattern//gn— count across the whole file:'<,'>s/pattern//gn— count within a visual selection:5,20s/pattern//gn— count within a line range
Example
You want to know how many TODO comments are in a file:
:%s/TODO//gn
Vim prints:
14 matches on 11 lines
No changes are made to the buffer. The message tells you both the total match count and how many lines contain the pattern.
Tips
- Combine with
\cfor case-insensitive counting::%s/\ctodo//gn - Use
nalone (withoutg) to count only the first match per line::%s/pattern//n - This works with the full power of Vim's regex engine, so complex patterns are fine:
:%s/\v^\s*#.*//gncounts comment lines - The last search pattern is updated, so pressing
nafterward will jump through matches