Count Occurrences

3.7
(341)

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.

How useful was this tip?

Average rating 3.7 / 5. Vote count: 341

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

90 Posts

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

1 thought on “Count Occurrences”

  1. The /g flag does not modify the range. (This is what the ‘%’ is for.) The /g flag makes the substitution work on multiple occurrences in a line! The default is to only replace the first occurrence of the search pattern in each line of the range. Thus, a reply like “12 occurrences in 9 lines” could only happen with /ng modifiers; with /n alone you would get “9 occurrences in 9 lines”.

Leave a reply

Your email address will not be published. Required fields are marked *