Question

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?

Was it helpful?

Solution

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.

OTHER TIPS

:help count-items

In VIM 6.3, here's how you do it.

:set report=0
:%s/your_word/&/g    # returns the count without substitution

In VIM 7.2, here's how you'd do it:

:%s/your_word/&/gn   # returns the count, n flag avoids substitution
:!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".

Put the cursor on the word you want to count and execute the following.

:%s/<c-r><c-w>//gn

See :h c_ctrl-r_ctrl-w

vimgrep is your friend here:

vimgrep pattern %

Shows:

(1 of 37)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top