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

14

4

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?

Nathan Long

Posted 2011-03-01T20:41:21.730

Reputation: 20 371

Answers

24

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()

garyjohn

Posted 2011-03-01T20:41:21.730

Reputation: 29 085

After looking at the help and experimenting, I see that 1) :r is short for "read" (so you can type out 'read' or just 'r' and it's the same command), and 2) doing :r path/to/foo.txt will insert the contents of that file after the cursor. – Nathan Long – 2011-03-02T11:50:26.147

Also - I didn't know about the system call. That's awesome! – Nathan Long – 2011-03-02T11:51:20.840

1I also didn't know you could manually set registers like let @a = 'foo'. One cool idea would be, after doing a search and replace, you could save the search term to a register for pasting elsewhere by doing let @a = @/ - "make the a register contain what the / register contains, namely, my last search." – Nathan Long – 2011-03-02T11:53:34.007

1@Nathan Long: You're welcome. Other ways to paste from the / register are 1) to execute :put / to put the register contents on the next line and 2) while in insert mode, to type Ctrl-R followed by / to insert the register contents at the cursor position. For more on those, see :help :put and :help i_CTRL-R. – garyjohn – 2011-03-02T15:25:30.853