Get the filename after find -name | xargs

findgrepterminalxargs

I've a multiple jar directory in which I would like to locate some classes. I found a solution to see if a Class exists with the following command :

find -name "*.jar" | xargs -n 1 jar tf | grep 'myClass'

The problem is that I can't see in which jar it is located.

I'm looking for a solution to display the filename in my terminal. My current output is like that :

[user@server lib]$ find -name "*.jar" | xargs -n 1 jar tf | grep  'RollOn'  
com/ventyx/utils/logutils/rolling/RollOnDemandAppender.class

Any suggestions?

Best Answer

With GNU grep:

find . -type f -name '*.jar' -exec sh -c '
   for file do
     jar tf "$file" | grep -H --label="$file" myClass
   done' sh {} +

Or use awk for instance:

find . -type f -name '*.jar' -exec sh -c '
   export FILE
   for FILE do
     jar tf "$FILE" | awk '\''/myClass/ {
       print ENVIRON["FILE"] ": " $0}'\''
   done' sh {} +

You can also use bsdtar (as jar files are zip files and bsdtar supports them) to do the matching by itself (allowing you to have a more verbose output with files metadata without running the risk of grep matching on that metadata), though you'd still need something like grep to insert the filename:

find . -type f -name '*.jar' -exec sh -c '
   for file do
     bsdtar tvf "$file" "*myClass*" | grep -H --label="$file" "^"
   done' sh {} +
Related Question