A frequently used feature of Vim for me is filtering a file (or a selection of text) through an external command and replace the selection with the result, e.g.:
:'<,>'!sort
so
c
b
a
will be sorted and will result in
a
b
c
It’s also possible to replace the current line with the return value of an external command, e.g.:
:,!ls | wc -l
will insert the number of files in the current directory (in my case e.g.:)
41
But is there a way to pass the string to a command for the shell?
As an example, this might be the content of my visual selection:
line_x
line_y
line_z
I need to execute some shell command and take each of the selected lines as one shell script parameter, e.g.:
my_bash_command line_x -c -e -f
my_bash_command line_y -c -e -f
my_bash_command line_z -c -e -f
What is the best way to do this?
I suggest you use
xargs -L1Example:
Basically
xargs [cmd]will run the following[cmd]with multiple parameters from multiple lines. But with the-L1argument the[cmd]will be executed command for each line.If you need to supply a certain order to the arguments for your command you can use
xargs‘s-Ioption to supply a pattern to be replaced by the argument list.Example:
If you feel very adventurous you can just execute the code directly like so: