Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

xargs with multiple commands

Tags:

bash

xargs

In the current directory, I'd like to print the filename and contents in it. I can print filenames or contents separately by

find . | grep "file_for_print" | xargs echo
find . | grep "file_for_print" | xargs cat

but what I want is printing them together like this:

file1
line1 inside file1
line2 inside file1
file2
line1 inside file2
line2 inside file2

I read xargs with multiple commands as argument and tried

find . | grep "file_for_print" | xargs -I % sh -c 'echo; cat;'

but doesn't work. I'm not familiar with xargs, so don't know what exactly "-I % sh -c" means. could anyone help me? thank you!

like image 890
user987654 Avatar asked Sep 11 '13 02:09

user987654


People also ask

How do I pass multiple commands in xargs?

To run multiple commands with xargs , use the -I option. It works by defining a replace-str after the -I option and all occurrences of the replace-str are replaced with the argument passed to xargs.

What can I use instead of xargs?

If you can't use xargs because of whitespace issues, use -exec . Loops are just as inefficient as the -exec parameter since they execute once for each and every file, but have the whitespace issues that xargs have.

How do you pass arguments to xargs?

The -c flag to sh only accepts one argument while xargs is splitting the arguments on whitespace - that's why the double quoting works (one level to make it a single word for the shell, one for xargs).

Does xargs run in parallel?

xargs will run the first two commands in parallel, and then whenever one of them terminates, it will start another one, until the entire job is done. The same idea can be generalized to as many processors as you have handy. It also generalizes to other resources besides processors.


2 Answers

In this specific case, each command is executed for each individual file anyway, so there's no advantage in using xargs. You may just append -exec twice to your 'find':

find . -name "*file_for_print*" -exec echo {} \; -exec cat {} \;

In this case-print could be used instead of the first echo as pointed out by rici, but this example shows the ability to execute two arbitrary commands with a single find

like image 161
tavvit Avatar answered Oct 19 '22 07:10

tavvit


find . | grep "file_for_print" | xargs -I % sh -c 'echo %; cat %;' (OP was missing %s)

like image 30
necromancer Avatar answered Oct 19 '22 07:10

necromancer