112

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?

168

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.

  • 8
    even more cumbersome, but at least it is now official that there is no elegant way... – Paul Oyster Sep 16 '08 at 9:22
  • 53
    If you've already performed a search using /, it becomes just :%s///gn – Peter Gibson Jun 18 '09 at 2:50
  • So just add it to your .vimrc – JESii Mar 13 '14 at 15:16
  • 3
    I found quite useful following mapping: nnoremap <leader>n :%s///gn <CR> to count occurrences of the last search – Ikar Pohorský Aug 4 '15 at 11:16
  • 1
    There's no way to make this count go into a variable right? That's what I need... – Steven Lu Apr 2 '16 at 19:37
9
: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
  • I had a big file and following this approach was much quicker than grep. – Jai Prakash Apr 12 '16 at 7:01
5
:!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.

  • 7
    More simply :!grep -c "pattern" % – Iazel Mar 6 '14 at 16:47
2

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

1

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

-1

vimgrep is your friend here:

vimgrep pattern %

Shows:

(1 of 37)
  • 7
    This does not count occurences, but counts lines containing the pattern. So if pattern occers twice in a line, it would only be counted once. – sotto Mar 20 '12 at 7:40

Your Answer

By clicking ā€œPost Your Answerā€, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.