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 liness/pattern//— the substitute command with an empty replacementg— count every match on a line, not just the firstn— 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
nflag suppresses all side effects — registers, history, and cursor position are unaffected - Combine with
\cfor case-insensitive counting::%s/todo//gni - Use
\vfor a cleaner regex::%s/\v(foo|bar)//gncounts matches of either word - Pair with
gnmotion to then navigate through the found matches