I want to find the number of times 'x' is present in my file, so I submit %s/x//gn and get the correct answer.

How can I capture the resultant count into a variable using vimscript on the command-line?

The following solution was hinted at by an answer below:

:let cnt=0
:g/x/let cnt=cnt+1
:echo cnt

However, cnt is made to store the total number of lines in the buffer that have an x, not how many xs there are in the whole file.

So, the original question still stands.

link|improve this question

feedback

3 Answers

This is answered by the Vim FAQ "How do I count the number of times a particular word occurs in a buffer?"

link|improve this answer
The link you have mentions the command :g, which can be used to count lines where a regex matches, but not the number of times it matches on a line, which is what I need. – drapkin11 Mar 30 '11 at 18:19
@drapkin11: Good point. I know it could be done with a Vim script, but I'm not aware of a more elegant way to do it. – Heptite Mar 30 '11 at 21:25
feedback

You can try this

:let cnt=0
:g/^.*may/let cnt=cnt+1
:echo cnt

So you will then see how many lines have the word 'may' in them at least once. So the following text will be counted as 1:

Your mileage may vary. You may have already won.

Easy.

link|improve this answer
thanks, but this is too similar to @Heptite's suggestion, which does not resolve my original question. Note that I need to have a count of all instances of a match on each line - not just one. – drapkin11 Mar 30 '11 at 22:18
feedback
up vote 0 down vote accepted

The following does the trick:

:echo eval(join(map(range(1, line('$')), 'len(substitute(getline(v:val),"[^x]","","g"))')," + "))

This replaces all non-x characters with nothing, counts the number of remaining characters (should be xs), and adds up this result for each line in the file.

I got the idea for this technique using the map function from Dennis Williamson, in another post on Vim scripting.

link|improve this answer
feedback

Your Answer

 
or
required, but never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.