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:
Thanks a lot. Can't remember how many times I've substituted a word just to press U immediately :-D
A good tip, but it would be a good idea to reword this:
> the trailing g flag indicates that the entire address range % (which means all lines) should be included in the substitution (think “global”).
The `/g` flag does ensure substitution on the entire range, but that's because it affects each individual line. If it's missing, the entire address range will *still* be affected, it'll just apply to only one occurrence per line.