How can I get a numeric return value from an Ex command. For example, if I want to set a variable to the number of times a pattern occurs in a buffer. I tried this:
but I get the error "Unknown function exe".
Vi and Vim Stack Exchange is a question and answer site for people using the vi and Vim families of text editors. It only takes a minute to sign up.Sign up to join this community
The function is
exe(). Command names can be abbreviated, not functions.
The answer to your question "how can I get a numeric return value from a command" is "call a command that returns a number". ;) No seriously. Your assignment to a variable is valid. But your example won't work as
execute() returns the string that is returned by the
:s call. And in fact
execute() always returns strings so you'll never get a number from it. But a numerical string will often do and if you really need a number you can wrap a command/function that returns a string in
I think that answers your question, but turning to your example we can get a numerical string answer as follows.
The string returned by
:s is of the form
X matches on Y lines so if you want to extract the number of matches you can use this:
let answer=substitute(execute('%s/xyz//n'), ' .*', '', 'g')
It just strips off everything from the first space on leaving the first number. A bit hacky.