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

How do I count substitution matches before changing anything?

Answer

:%s/pattern/replacement/gn

Explanation

When you are about to run a broad substitution, it is often safer to measure impact first. :%s/pattern/replacement/gn gives you a dry-run count of matches without modifying the buffer. This is especially useful before project-wide edits or when your regex is complex and you want confidence before you mutate text.

How it works

  • :%s runs substitution over the entire buffer
  • pattern is the search regex you want to audit
  • replacement is parsed but not applied because of the n flag
  • g counts all matches per line, not just the first
  • n reports counts only (no text changes)

Example

Given:

TODO(api): add retries
TODO(ui): align button spacing
done: write tests
TODO(api): add timeout

Run:

:%s/TODO/done/gn

Vim reports a match count (for example, 3 matches on 3 lines) and leaves the buffer unchanged.

Tips

  • Use :%s/pattern/replacement/gc after this if you want interactive confirmations.
  • :s/pattern/replacement/gn limits the count to the current line.
  • For line-count style reporting instead of match-count style, compare with n without g depending on your pattern behavior.

Next

How do I populate a window-local location list from the current file and open it immediately?