In Vim, what’s an elegant way to grab output from the command-line

vim

If I'm in Vim and want to get some output from the command-line and tack it onto my current file, I can run this:

:! echo "foo" >> %

That will append "foo" to my current file, and I'll have to reload.

Is there a more elegant way to do this – have that output go into a buffer that I can paste, for example?

Best Answer

Yes:

:r !echo "foo"

See

:help :r!

That will insert the output of the command after the current line. If you want to capture the command output into a register that you can paste, you can do this:

:let @a = system('echo "foo"')

Now the output of the command (including the trailing newline) is in register a. See

:help let-@
:help system()
Related Question