vimtricks.wiki Concise Vim tricks, one at a time.

How do I capture shell command output directly into a Vim register?

Answer

:let @a = system('cmd')

Explanation

You can populate any Vim register with the output of an external shell command using :let @{register} = system('{command}'). This is far more flexible than :read !cmd because the output goes into a register you can paste anywhere—multiple times, in different locations—without it appearing inline immediately.

How it works

  • :let @a = ... assigns a value to register a using Vimscript's :let command
  • system('{command}') calls the shell and returns its stdout as a string
  • The result is stored in the register and can be pasted with "ap in normal mode or <C-r>a in insert mode

Example

Capture today's date into register d:

:let @d = system('date +"%Y-%m-%d"')

Then paste it anywhere with "dp or <C-r>d in insert mode.

Capture a git commit hash:

:let @g = system('git rev-parse --short HEAD')

Note: system() appends a trailing newline to the output. Strip it with trim():

:let @g = trim(system('git rev-parse --short HEAD'))

Tips

  • Use "=system('cmd')<CR>p as a one-shot expression register paste if you don't need to store it
  • Register contents persist for the session, so you can capture once and paste many times
  • You can also write back: :call system('xclip', @a) pipes register a to an external command

Next

How do I match a pattern only when it is preceded or followed by another pattern, without including that context in the match?