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

How do I execute the current line as a shell command and insert the output?

Answer

:.!sh

Explanation

The :.!sh command pipes the current line to a shell, executes it, and replaces the line with the command's output. This turns any line in your buffer into a live shell command — write the command, run it in place, and get the results without leaving Vim.

How it works

  • . is a range specifying the current line
  • ! is the filter operator, which sends the range to an external command's stdin
  • sh is the shell that interprets and executes the input
  • The output of the shell command replaces the original line in the buffer

Vim sends the current line's text as stdin to sh, which executes it, and the stdout replaces the line.

Example

You have a line in your buffer:

date +%Y-%m-%d

With the cursor on that line, run :.!sh. The line is replaced with today's date:

2025-01-15

Another example — generate a sequence:

seq 1 5

After :.!sh:

1
2
3
4
5

You can even run multi-step pipelines:

echo 'hello world' | tr a-z A-Z

After :.!sh:

HELLO WORLD

Tips

  • Use !!sh as a normal mode shortcut — !! is equivalent to :.! for the current line
  • If you want to keep the original command and insert the output below it, use :read !command instead: :read !date +\%Y-\%m-\%d
  • Select multiple lines in visual mode and run :'<,'>!sh to execute them all as a script
  • Use :.!python3 to execute the current line as Python, or :.!node for JavaScript — any interpreter works
  • Undo with u if the output isn't what you expected — the replacement is a single undo step
  • Combine with the expression register for simpler calculations: <C-r>=system('date')<CR> inserts output in insert mode without replacing anything
  • This technique is a cornerstone of "literate programming" in Vim — write commands inline, execute them, and capture results directly in your document

Next

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