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

How do I count the number of pattern matches in a file without making substitutions?

Answer

:s/pattern//gn

Explanation

The :s///gn command counts how many times a pattern appears in the file without actually replacing anything. The n flag suppresses the substitution and instead reports the match count, making it a quick way to audit your file before committing to a large :substitute operation.

How it works

  • :s/pattern// is the substitute command with an empty replacement
  • g makes it global (count all matches on each line, not just the first)
  • n suppresses the actual substitution and prints the count instead

Combine with a range to scope the count:

  • :%s/pattern//gn — count across the whole file
  • :'<,'>s/pattern//gn — count within a visual selection
  • :5,20s/pattern//gn — count within a line range

Example

You want to know how many TODO comments are in a file:

:%s/TODO//gn

Vim prints:

14 matches on 11 lines

No changes are made to the buffer. The message tells you both the total match count and how many lines contain the pattern.

Tips

  • Combine with \c for case-insensitive counting: :%s/\ctodo//gn
  • Use n alone (without g) to count only the first match per line: :%s/pattern//n
  • This works with the full power of Vim's regex engine, so complex patterns are fine: :%s/\v^\s*#.*//gn counts comment lines
  • The last search pattern is updated, so pressing n afterward will jump through matches

Next

How do I define or modify a macro directly as a string without recording it?