Archive for January, 2009

Counting occurrence of a particular word in Vim

Wednesday, January 28th, 2009

There is no built in word count feature in Vim, but a simple use of the substitute command can be used for the same purpose.

:%s/word//gn

Vim returns something along the lines of:

14 matches on 47 lines

Basically we are performing a search and replace but telling Vim not to take any action. If we break down the command we can see how it works.

:s – is the substitute command (find and replace)

% – putting the ‘%’ in front tells Vim to substitute across the whole file (not just this line)

<word> – this is the word we are counting (it could also be a regex expression, see below)

g – the ‘g’ switch tells Vim to search the whole line (globally) and not stop after the first match

n – the ‘n’ switch tells Vim to take ‘N’o action. This is what we want as we are only counting.

UsingĀ  regex:

Usually this command counts all occurrences of the word, but we can make it more useful with a sprinkling of regex. Say you want to count all lines that begin with comments (shell style):

:%s/^#//gn

Or all lines that are empty or only contain whitespace:

:%s/^\s*$//gn

The source of this tip is from the tips built into the Vim online help. If you enter the following command, you will get the help page version of what I have documented here (took me a while to track this down inside Vim).

:h count-items