2

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.

3 Answers 3

1

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

2
  • 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
    Commented Mar 30, 2011 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
    Commented Mar 30, 2011 at 21:25
0

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.

1
  • 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
    Commented Mar 30, 2011 at 22:18
0

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.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .