41

Is it possible to run an external command and store its output in a register?

  • :redir works for ex commands, not for external commands (afaik)
  • :r ! runs the external command but directly inserts output into the current buffer
Matteo Riva
  • 24,728
  • 12
  • 72
  • 104

2 Answers2

51

Found the answer thanks to a user on the vim-use mailing list:

:let @a = system("ls -l")

To run a command with the file under the cursor as argument:

:let @a = system("ls -l " . shellescape(expand('<cfile>')))

Matteo Riva
  • 24,728
  • 12
  • 72
  • 104
  • 2
    It's wise to use the `shellescape()` function when building shell commands. In this example, `:let @a = system("ls -l " . shellescape(expand('')))`. – jamessan Jan 25 '10 at 15:38
  • 1
    Also note that system takes a second argument which it pipes to the command as stdin, so you can e.g. yank a visual selection to a register and then pipe that register to the command `let foo = system("command here", @a)` – n8henrie Jan 28 '20 at 18:37
0

:redir does seem to work, though a little clunky. If you're looking to pipe data from your file into the external command it may be easier.

:redir @a
:w ! ls -1
:redir END
"ap

EDIT: Interestingly, I just noted that it seems to be working for me in neovim v0.4.3 but not in vim 8.2.100 (MacOS 10.15.2, both installed via homebrew).

n8henrie
  • 2,737
  • 3
  • 29
  • 45