Using Vim to Count Patterns

The other day, I posted a trick on using Vim with flat files.  Well, today, I wanted to count the number of times certain data conditions appeared in my file.  I created statistics on my program to show the count, but I wanted to check them to make sure the code was right.  I found this command would do the trick in Vim:

:%s/<pattern>//n

The “s” is the part that does a search and replace, but the “n” tells it to only count the matches rather than replace it with anything.  So, if I wanted to count the number of lines with “0” in the 123rd position, I would use this:

:%/^.\{122}0//n

Here is where I found the trick:

Wiki Technology – Vim: Count number of matches of a pattern

One thought on “Using Vim to Count Patterns

Leave a Comment

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.