Count Occurrences


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:


…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.

How useful was this tip?

Average rating 3.9 / 5. Vote count: 815

No votes so far! Be the first to rate this tip.

We are sorry that this post was not useful for you!

Let us improve this post!

Tell us how we can improve this post?

Written by

Colin Bartlett

105 Posts

Vim enthusiast and software developer for more than 20 years.
View all posts