Counting occurrences in Vim without marking the buffer changed

Vim

Vim Problem Overview


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?

Vim Solutions


Solution 1 - Vim

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.

Solution 2 - Vim

: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

Solution 3 - Vim

:!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.

Solution 4 - Vim

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

Solution 5 - Vim

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

Solution 6 - Vim

vimgrep is your friend here:

vimgrep pattern %

Shows:

(1 of 37)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionPaul OysterView Question on Stackoverflow
Solution 1 - VimBruno De FraineView Answer on Stackoverflow
Solution 2 - VimkonyakView Answer on Stackoverflow
Solution 3 - VimIlyaView Answer on Stackoverflow
Solution 4 - VimredactedView Answer on Stackoverflow
Solution 5 - VimSagar JainView Answer on Stackoverflow
Solution 6 - VimrdeitsView Answer on Stackoverflow