How to capture the result of a regex-powered command in Vim normal mode?

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.

drapkin11

Posted 2011-03-30T14:03:36.580

Reputation: 646

Answers

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.

drapkin11

Posted 2011-03-30T14:03:36.580

Reputation: 646

1

Heptite

Posted 2011-03-30T14:03:36.580

Reputation: 16 267

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 – 2011-03-30T18:19:52.037

@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 – 2011-03-30T21:25:47.720

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.

Rolnik

Posted 2011-03-30T14:03:36.580

Reputation: 1 457

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 – 2011-03-30T22:18:33.233