How to search multiple jar files for a string or pattern (shell script)

Here’s a Unix shell script that I use to search Java Jar files for any type of string pattern. You can use it to search for the name of a class, the name of a package, or any other string/pattern that will show up if you manually ran jar tvf on each jar file. The advantage of this script — if you’re a Unix, Linux, or Cygwin user — is that it will search through all jar files in the current directory:

#!/bin/sh

LOOK_FOR="codehaus/xfire/spring"

for i in `find . -name "*jar"`
do
  echo "Looking in $i ..."
  jar tvf $i | grep $LOOK_FOR > /dev/null
  if [ $? == 0 ]
  then
    echo "==> Found \"$LOOK_FOR\" in $i"
  fi
done

Sample output: jar files that match regex pattern

This shows how I run this shell script, and the output from it:

$ ./searchjars.sh

Looking in ./activation-1.1.jar ...
Looking in ./commons-beanutils-1.7.0.jar ...
Looking in ./commons-codec-1.3.jar ...
Looking in ./commons-pool.jar ...
Looking in ./jaxen-1.1-beta-9.jar ...
Looking in ./jdom-1.0.jar ...
Looking in ./mail-1.4.jar ...
Looking in ./xbean-2.2.0.jar ...
Looking in ./xbean-spring-2.8.jar ...
Looking in ./xfire-aegis-1.2.6.jar ...
Looking in ./xfire-annotations-1.2.6.jar ...
Looking in ./xfire-core-1.2.6.jar ...
Looking in ./xfire-java5-1.2.6.jar ...
Looking in ./xfire-jaxws-1.2.6.jar ...
Looking in ./xfire-jsr181-api-1.0-M1.jar ...
Looking in ./xfire-spring-1.2.6.jar ...
==> Found "codehaus/xfire/spring" in ./xfire-spring-1.2.6.jar
Looking in ./XmlSchema-1.1.jar ...

I omitted a bunch of output there, but I hope you get the idea. This script can easily search dozens or hundreds of jar files if need be.

To improve this script I recommend two things. First, take the pattern you want to look for as a command-line argument instead of hard-coding it inside the script as I’ve done here. Second, search through all jar files in all sub-directories of the current directory. Both of these are easily done, and I’ll update this blog if/when I do that.