xargs with multiple commands

user987654 picture user987654 · Sep 11, 2013 · Viewed 21.4k times · Source

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!

Answer

necromancer picture necromancer · Sep 11, 2013

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