Category: Vim

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:


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:


Here is where I found the trick:

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

Vim Search in Flat Files

I have been working with Flat Files recently, and I found Vim Search patterns can help with finding certain conditions within the file.  This pattern works very well:


Searches for n number of the preceding pattern.

For example, say you want to find any lines in the file that have a “2” in the 51st position of the file.  You can use this pattern:


So, this matches 50 characters of anything and a “2” following.


Softpanorama: Vim Regular Expressions