vimtricks.wiki Concise Vim tricks, one at a time.

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 file
  • s/pattern// — substitute with an empty replacement (but the n flag prevents this)
  • g — count all occurrences on each line, not just the first
  • n — report-only mode: shows a N matches on M lines message 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 n flag can be combined with other flags like i (case-insensitive): :%s/pattern//gni
  • Unlike :vimgrep, this method is instant — no quickfix list, no file scanning
  • The last search pattern (@/) is updated to pattern, so you can immediately press n to jump to the first match
  • Use \v for cleaner regex: :%s/\v(foo|bar)//gn

Next

How do I match a pattern only when it is preceded or followed by another pattern, without including that context in the match?