Counting occurrences in Vim without marking the buffer changed

Viewed 37088

In order to know how many times a pattern exists in current buffer, I do:

:%s/pattern-here/pattern-here/g

It gives the number of occurrences of the pattern, but is obviously cumbersome and also has the side-effect of setting the 'changed' status.

Is there a more elegant way to count?

6 Answers

To avoid the substitution, leave the second pattern empty, and add the ā€œnā€ flag:

:%s/pattern-here//gn

This is described as an official tip.

:!cat %| grep -c "pattern"

It's not exactly vim command, but it will give you what you need from vim.
You can map it to the command if you need to use it frequently.

The vimscript IndexedSearch enhances the Vim search commands to display "At match #N out of M matches".

Related