In the function-list, it gives execute() as running an ex command, but it does not seem to be returning a string as I expect.

For example, if I run this on a file that has 'abc' in it somewhere:

:echo execute("%s/abc//gen")

Then it answers: "1 match on 1 line". Then if make the following command:

:echo str2nr("1 match on 1 line")

Then it returns the number 1 on the status line. However, finally, if I run this:

:echo str2nr(execute("%s/abc//gen"))

Then it returns 0 on the status line, not 1 as expected. What is going wrong here?

1 Answer 1


The reason is that the result of execute("%s/abc//gen") is not the same as the string "1 match on 1 line", but "\n1 match on 1 line". When you echo this, it outputs as expected, but with str2nr, the initial newline leads to your unexpected 0 return value.

As is described in :help execute(), you can use split to get a list of lines of the output. So, this should work:

echo str2nr(join(split(execute('%s/abc//gen'), "\n")))
  • Huh, how could I have determined the exact string that execute is returning? Is there a way to print out the string with unprintable characters shown as codes? Commented Feb 2, 2018 at 19:09
  • I'm not sure about showing unprintable characters, but you can see the output with something like :echo 'x' . func(...) . 'y'. Commented Feb 2, 2018 at 23:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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