How do I count how many times a pattern appears in a file without making any changes?
Answer
:%s/pattern//gn
Explanation
The n flag on the substitute command reports the number of matches without performing any substitution. Combined with % (whole file) and g (all occurrences per line), :%s/pattern//gn gives you an instant occurrence count — no changes made, no undo needed.
How it works
%— range covering the entire files/pattern//— substitute with an empty replacement (but thenflag prevents this)g— count all occurrences on each line, not just the firstn— report-only mode: shows aN matches on M linesmessage and does nothing
Because no substitution actually occurs, the buffer is not modified and the undo history is unaffected.
Example
To count all occurrences of TODO in a file:
:%s/TODO//gn
Vim displays something like:
7 matches on 5 lines
To count occurrences only in the current line:
:s/pattern//gn
To count within a visual selection:
:'<,'>s/pattern//gn
Tips
- The
nflag can be combined with other flags likei(case-insensitive)::%s/pattern//gni - Unlike
:vimgrep, this method is instant — no quickfix list, no file scanning - The last search pattern (
@/) is updated topattern, so you can immediately pressnto jump to the first match - Use
\vfor cleaner regex::%s/\v(foo|bar)//gn