How do I count the number of matches for a search pattern?
Answer
:%s/pattern//gn
Explanation
The :%s/pattern//gn command counts how many times a pattern appears in the file without making any changes. The secret is the n flag, which tells Vim to report the number of matches instead of actually performing the substitution.
How it works
:%sruns the substitute command on every line in the file/pattern/is the search pattern to count//is an empty replacement string (irrelevant since no replacement happens)gcounts all matches per line, not just the firstnprevents any actual substitution — it only reports the count
Vim displays a message like 42 matches on 15 lines in the command line area.
Example
Given the text:
foo bar foo
baz foo
foo foo foo
Running :%s/foo//gn reports:
6 matches on 3 lines
No text is modified — the command only counts.
Tips
- Without the
gflag,:%s/pattern//ncounts the number of lines containing the pattern (one match per line) - You can use a visual selection instead of
%to count matches in a specific range - Use
:%s/\<word\>//gnto count whole-word matches only - Use
:%s/pattern//gnifor case-insensitive counting - After searching with
/patternor*, you can use:%s///gnwith an empty pattern to count the last searched term - This is much faster than manually scrolling through results with
n