Execute shell command without filtering from Vim
Select your block of text, then type these keys :w !sh
The whole thing should look like:
:'<,'>w !sh
That's it. Only took me 8 years to learn that one : )
note: typing : after selecting text produces :'<,'> a range indicating selection start and end.
Update 2016: This is really just one use of the generic:
'<,'>w !cli_command
Which basically lets you "send" arbitrary parts of your file to external commands and see the results in a temporary vi window without altering your buffer. Other useful examples would be:
'<,'>w !wc'<,'>w !to_file my_file
I honestly find it more useful to alter the current buffer. This variety is simply:
'<,'>!wc'<,'>!to_file my_file
One possibility would be to use system()
in a custom command, something like this:
command! -range -nargs=1 SendToCommand <line1>,<line2>call SendToCommand(<q-args>) function! SendToCommand(UserCommand) range " Get a list of lines containing the selected range let SelectedLines = getline(a:firstline,a:lastline) " Convert to a single string suitable for passing to the command let ScriptInput = join(SelectedLines, "\n") . "\n" " Run the command let result = system(a:UserCommand, ScriptInput) " Echo the result (could just do "echo system(....)") echo resultendfunction
Call this with (e.g.):
:'<,'>SendToCommand wc -w
Note that if you press V%:
, the :'<,'>
will be entered for you.
:help command:help command-range:help command-nargs:help q-args:help function:help system():help function-range
Update: my answer is nonsense.
@pixelearth's answer is good, but I had a little trouble understanding what he did exactly, so I wrote the following. This sequence of commands let's you execute wc -l
on your visual selection. wc -l
simply counts the number of lines passed to it.
- In Vim go into Visual Mode using
v
- Select a few lines by going down:
jjjj
- Type
:
which Vim will translate to:'<,'>
- Type
w !wc -l
, your complete commandline should now be:'<,'>w !wc -l
- Press Enter to get the result of your command (in this example it would be 4)
- Press Enter to continue editing
I don't understand what exactly happens at step 3 and 4 but I do know that it works.