Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to build and run a shell command based on the contents of several lines in Vim?

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?

like image 931
oliver Avatar asked Jul 20 '11 13:07

oliver


1 Answers

I suggest you use xargs -L1

Example:

:%!xargs -L1 wc -l

Basically xargs [cmd] will run the following [cmd] with multiple parameters from multiple lines. But with the -L1 argument 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 -I option to supply a pattern to be replaced by the argument list.

Example:

:%!xargs -L1 -I {} rake {} --trace

If you feel very adventurous you can just execute the code directly like so:

:%!bash
like image 173
Peter Rincker Avatar answered Oct 15 '22 00:10

Peter Rincker