Vim: Pipe selected text to shell cmd and receive output on vim info/command line

For multi line version you can do this after selecting the text:

:'<,'>:w !command<CR>

You can map it to simple visual mode shortcut like this:

xnoremap <leader>c <esc>:'<,'>:w !command<CR>

Hit leader key + c in visual mode to send the selected text to a stdin of the command. stdout of the command will be printed below vim's statusbar.

Real world example with CoffeeScript:

https://github.com/epeli/vimconfig/commit/4047839c4e1c294ec7e15682f68563a0dbf0ee6d


I would do it like this:

Place this function in your vimrc:

function Test() range
  echo system('echo '.shellescape(join(getline(a:firstline, a:lastline), "\n")).'| pbcopy')
endfunction

This will allow you to call this function by doing:

:'<,'>call Test()

Then you can also map that like this (just under the function declaration in your vimrc):

com -range=% -nargs=0 Test :<line1>,<line2>call Test()

So you can call the function doing this:

:'<,'>Test

Note: :<','> are range selectors, in order to produce them just select the pertinent lines in visual mode and then go to command mode (pressing the colon key)


Simply highlight the lines using visual line select shift-v, the hit :! and type the command you wish to send the commands to. The resulting output will then replace your selected text.

When you type your command it will appear at the bottom as:

:'<,'>!somecmd

the '<,'> is indicating that the range you have visually selected will be passed to the command specified after the !