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?
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:
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.
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.
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.
That’s it! Do you know more tricks using substitute (s) command in vim? Please let us know in the comment section.