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

How do I insert the output of a shell command into my file?

Answer

:r !command

Explanation

The :r !command command executes a shell command and inserts its output directly into the current buffer below the cursor line. This is one of Vim's most powerful integrations with the Unix shell, letting you pull in data from any external program without leaving your editor.

How it works

  • :r is the read command, which normally reads a file into the buffer
  • ! tells Vim to interpret what follows as a shell command instead of a filename
  • The output of the command is inserted on the line below the cursor

Example

To insert the current date and time into your file:

:r !date

This might insert something like:

Thu Jun 12 14:30:00 UTC 2025

To insert a directory listing:

:r !ls -la

To insert the contents of your clipboard (macOS):

:r !pbpaste

Tips

  • Use :r filename (without !) to insert the contents of a file instead of a command's output
  • Use :0r !command to insert the output at the very top of the file (before line 1)
  • Use :.!command to replace the current line with the command's output instead of inserting below it
  • Use :%!command to pipe the entire file through a command and replace it with the output (e.g., :%!sort to sort the whole file, :%!python -m json.tool to format JSON)
  • In visual mode, select lines and type !command to filter the selection through the command — the selected text is sent as stdin and replaced with the output
  • Use :r !curl -s https://example.com to fetch a URL and insert the response directly into your buffer
  • Use !!command in normal mode as a shortcut for :.!command — it filters the current line through the command

Next

How do I edit multiple lines at once using multiple cursors in Vim?