Count Occurrences

Get a pattern match count quickly with this one simple Vim trick.

One of the most commonly used commands in Vim is the substitute command :s. It’s often applied to an entire file in the form :%s/match/replacement/g. After the trailing slash, you can apply flags which change the behavior of the match. In this case, the trailing g flag indicates that the entire address range % (which means all lines) should be included in the substitution (think “global”). You could also visually select a range of lines and substitute within that selection.

But what if you don’t want to actually match and substitute but rather just count the occurrences of your pattern match? Vim has a handy pattern substitution flag n that can perform the search but ignore the substitution. Using the flag like so:

:%s/some_pattern//n

…will return the number of matches and the number of lines those matches occur on, without doing any substitution:

12 occurrences on 9 lines

In the screencast below, we show this count at work. The substitution command is used to count the number of times the pattern first_name occurs in the JSON provided:

There are many uses for this. Perhaps you’re writing prose in Vim and want to ensure you haven’t repeated the same word too many times.

A recent use case of mine involved trying to decide how to name a database column in a software project. I simply checked the database schema file for occurrences of several naming convention patterns. One occurred 60 times and one occurred 3 times, so naturally I named the column with the more prominent convention.

Try out /n next time you need to count occurrences of a word or pattern in Vim.


Was this useful? Help us improve!

With your feedback, we can improve VimTricks. Click a link to vote: