In vim, how to insert shell command output when executing contents of visual block

Viewed 272

With Vim, I often execute lines of a bash script while editing it, using :'<,'>w !bash after selecting the lines with visual block.

Now I want the output of command to be inserted in the script. How can I do that?

1 Answers

If you want your code to be replaced with its output, you can simply remove the w from your command. That leaves you with:

:'<,'>!bash`

which acts like a filter for the selected lines. See :help :!.

If you want to insert the output of your code below itself like so:

echo 1
1

you will need to be a little bit creative:

:'<,'>t'>|'[,']!bash
  • :[range]t[address] copies lines in [range] below line [address]. Here, we copy the visually selected lines below themselves.
  • | separates Ex commands.
  • '[,']!bash works like above: it filters the lines in the given range through bash. Here, the range covers the latest changed lines, in this case the lines we just copied. See :help '[.

Possible improvements…

  • Make the command less noisy with :help :silent:

    :'<,'>t'>|sil'[,']!bash
    
  • Prepend a comment character:

    :'<,'>t'>|sil'[,']!bash|sed 's/^/\# /'
    
  • Turn it into a visual mode mapping:

    xnoremap <key> :t'>\|sil'[,']!bash\|sed 's/^/\# /'<CR>
    
Related