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
:ris 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 !commandto insert the output at the very top of the file (before line 1) - Use
:.!commandto replace the current line with the command's output instead of inserting below it - Use
:%!commandto pipe the entire file through a command and replace it with the output (e.g.,:%!sortto sort the whole file,:%!python -m json.toolto format JSON) - In visual mode, select lines and type
!commandto filter the selection through the command — the selected text is sent as stdin and replaced with the output - Use
:r !curl -s https://example.comto fetch a URL and insert the response directly into your buffer - Use
!!commandin normal mode as a shortcut for:.!command— it filters the current line through the command