5

In example, I would like to paste the current time or date into editor by using external commands (such as date) without leaving vim.

How this can be achieved?

7

Simply run

:%!date

(or whatever command you wish to dump into the current buffer).

This will replace the entire buffer with the command's output. If you don't want this, use read instead:

:read !date

Or, you can replace a certain line with the output of an external command:

:2!date  replace line 2 with the current date
:$!date  replace the last line with the current date
:.!date  replace the current line with the current date

This also works with read, but appends after that line instead (ex. use :$read !date to append the current date to the file).

  • the reason I wanted to dump to editor was so I could search the output better. Is there not a way like cmd > vim or something? – Charlie Parker Mar 26 '18 at 13:48
4

A more complex example, to run a Python script on the current buffer, putting the output in a new tab:

:tabnew | r ! python -c "import json, sys; json.load(sys.stdin)" < #
  • tabnew opens a new tab
  • r is short for read
  • ! executes a shell command
  • python -c executes an inline python script
  • json.load(sys.stdin) tries to load (parse) json from stdin
  • < # redirects the previous buffer (the current one pre tabnew) into the command
  • note that json.tool works as well for this particular purpose, but I wanted to show something simple for redirection of # with an inline script. – gens Oct 23 at 17:25
  • Welcome to Vi and Vim! Nice answer demonstrating #—maybe mention % too? +1 from me, anyways. – D. Ben Knoble Oct 23 at 19:52
2

In addition Doorknob answer, it's also possible to use the shortcut for read as r!, in example:

:r!date

Some other useful example would include doing some math like calculating number of bytes in gigabyte:

:r! echo $((1024**3))
:r! echo $((1024*1024*1024))
  • 1
    Just wanted to add that bc can be good for quick math, i.e., :r! bc -l << '2^30'. – HAL 9001 Feb 15 '15 at 6:40
  • 1
    @HAL9001 I know this is dated, but for that kind of think I would just use <C-r>= – D. Ben Knoble Oct 23 at 19:53
1

A plugin I've been using to do this is clam.vim.

After installing it, you can do

:Clam date

to put the date in a new buffer. You can run pretty arbitrarily complex commands, so

:Clam find . -iname '*.vim'

or

:Clam ./my-script

is also possible.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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