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 registerausing Vimscript's:letcommandsystem('{command}')calls the shell and returns its stdout as a string- The result is stored in the register and can be pasted with
"apin normal mode or<C-r>ain 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>pas 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 registerato an external command