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

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

  • :%s runs 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)
  • g counts all matches per line, not just the first
  • n prevents 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 g flag, :%s/pattern//n counts 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\>//gn to count whole-word matches only
  • Use :%s/pattern//gni for case-insensitive counting
  • After searching with /pattern or *, you can use :%s///gn with an empty pattern to count the last searched term
  • This is much faster than manually scrolling through results with n

Next

How do I edit multiple lines at once using multiple cursors in Vim?