How to have xargs use its input in an arbitrary invocation
Here's a common pedestrian use of xargs:
ls *.rb | xargs echo
What this does is invoke echo
on a big list of all the files found by ls *.rb
But let's say you want to use the output of ls *.rb
in a more complicated way? You don't want the entire list to just be tacked onto the end of whatever command you give xargs. Maybe you want to do something like this with each file
cp file.rb file-new.rb
You can do this with the -I
flag! like so:
ls *.rb | xargs -I{} cp {} {}-new.rb
-I
is given a pattern that will be used for the replacement. {}
is what I found in examples online, and worked for me, so I'm using it here.
Note that when doing this, xargs will invoke the command once per file, and not just once for all files. If you want to invoke xargs once per file without needing the -I
substitution, you can do so with the -n
flag.