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?
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).
cmd > vim
or something?
Commented
Mar 26, 2018 at 13:48
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 tabr
is short for read
!
executes a shell commandpython -c
executes an inline python scriptjson.load(sys.stdin)
tries to load (parse) json from stdin< #
redirects the previous buffer (the current one pre tabnew
) into the commandjson.tool
works as well for this particular purpose, but I wanted to show something simple for redirection of #
with an inline script.
#
—maybe mention %
too? +1 from me, anyways.
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))
bc
can be good for quick math, i.e., :r! bc -l << '2^30'
.
<C-r>=
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.