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
:%sruns substitution over the entire bufferpatternis the search regex you want to auditreplacementis parsed but not applied because of thenflaggcounts all matches per line, not just the firstnreports 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/gcafter this if you want interactive confirmations. :s/pattern/replacement/gnlimits the count to the current line.- For line-count style reporting instead of match-count style, compare with
nwithoutgdepending on your pattern behavior.