6

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?

kenorb
  • 18,433
  • 18
  • 72
  • 134

4 Answers4

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

Doorknob
  • 15,237
  • 3
  • 48
  • 70
  • 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
5

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
gens
  • 151
  • 1
  • 1
  • 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 '19 at 17:25
  • Welcome to [vi.se]! Nice answer demonstrating #—maybe mention % too? +1 from me, anyways. – D. Ben Knoble Oct 23 '19 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))
kenorb
  • 18,433
  • 18
  • 72
  • 134
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.

D. Ben Knoble
  • 26,070
  • 3
  • 29
  • 65