1. Home
  2. Linux
  3. Count number of pattern matched in vim editor

Count number of pattern matched in vim editor

Question: How to count number of pattern matched in vim editor? I know to search a pattern in vim, but is there a command to know the total number of matches found for a searched pattern?

Solution:

Yes. It’s possible to use n flag with a substitute command s. For example, if you want to search a pattern called “sample”, then you need to use the below command:

:%s/sample//gn

The above command will display total number of matches found for a searched pattern and also tells total number of lines that had the searched pattern.

The below GIF demonstrates usage of the command.

Count number of pattern matched

The above command can be modified to restrict the search to a region (say, search a pattern from line 1 to 5 and display the count of matched pattern). To do that, replace % with a range as shown below.

:1,5s/sample//gn
Note:

% is used to search all lines.

The above command displays the number of pattern matched within line 1 to 5. But remember, the command will highlight all patterns found in the text.

Count number of pattern matched

That’s it! Do you know more tricks using substitute (s) command in vim? Please let us know in the comment section.

Updated on October 11, 2017

Was this article helpful?

Related Articles

Add A Comment