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 makes it report the match count without actually performing any replacement. Combining :%s/pattern//gn gives you a precise count of every occurrence in the entire file — a fast, non-destructive alternative to piping through external tools.

How it works

  • % — applies the command to all lines
  • s/pattern// — the substitute command with an empty replacement
  • g — count every match on a line, not just the first
  • n — dry-run mode: report the count only, make no changes

Vim prints something like 7 matches on 3 lines in the status bar.

Example

To count all occurrences of TODO in the current file:

:%s/TODO//gn

Output:

12 matches on 8 lines

To count only in a range (lines 50–100):

:50,100s/TODO//gn

To count inside a visual selection, first select lines in visual mode, then:

:'<,'>s/TODO//gn

Tips

  • The n flag suppresses all side effects — registers, history, and cursor position are unaffected
  • Combine with \c for case-insensitive counting: :%s/todo//gni
  • Use \v for a cleaner regex: :%s/\v(foo|bar)//gn counts matches of either word
  • Pair with gn motion to then navigate through the found matches

Next

How do I run text I've yanked or typed as a Vim macro without recording it first?