Tip 86Count the Matches for the Current Pattern

This tip shows a couple of ways that you can count the number of matches for a pattern.

Suppose we want to find out how many times the word “buttons” appears in this excerpt:

 var​ buttons = viewport.buttons;
 viewport.buttons.previous.show();
 viewport.buttons.next.show();
 viewport.buttons.index.hide();

We’ll start by searching for that word:

=> /\<buttons\>

Now we can move from one match to another by pressing the n and N keys, but Vim’s search command doesn’t give us any indication of how many matches are in the current document. We can get a match count by using either the :substitute or :vimgrep command.

Count Matches with the ‘:substitute’ Command

We can get a ...

Get Practical Vim, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.