Reputation:
I've found many examples on how to search for files that exist in a jar, but I want to find text that exists in a file that exists in a jar. How can I do this without unpacking all of my jar files?
#!/bin/sh
LOOK_FOR="string to find inside a file inside a jar"
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
Upvotes: 2
Views: 4996
Reputation: 28608
If you just want to see if any of the file in the jar contains a specific string ($LOOK_FOR
), but don't care about which file, you can do this with unzip
, here's a small test:
$ echo hello > a
$ echo world > b
$ jar cf qq.jar a b
$ jar tf qq.jar
META-INF/
META-INF/MANIFEST.MF
a
b
$ unzip -p qq.jar|grep hello
hello
With the -p
option, the files are unzipped to pipe (stdout).
If you want to know in which file the string is, I don't think you can do anything better than unpack.
Upvotes: 4
Reputation: 350
Here is nearly the same, but with some arguments added and a grep return giving the entire line. I use this to control in a lot of jars some properties, or anything text related.
#!/bin/sh
# This script is intended to search for named jars ($LOOK_IN_JAR) from a given directory ($PLACE_IN).
# then the list of jars should be opened to look into each one for a specific file ($LOOK_FOR_FILE)
# if found, the file should be grep with a pattern ($PATTERN) which should return the entire line
#
# content of $LOOK_FOR_FILE (properties files) are like :
# key=value
# key2 = value2
# key3= value3
#
# the script should return in console something like :
# found in /path/to/foo.jar :
# pattern=some value
# found in /path/to/bar.jar :
# pattern = another value
# etc.
PLACE_IN=.
LOOK_IN_JAR=*.jar
LOOK_FOR_FILE=""
PATTERN=""
if [ -z "$1" ]
then
echo "at least 2 arguments are mandatory : pattern and files to grep in"
else
PATTERN=$1
echo "Looking for pattern : $PATTERN"
fi
if [ -z "$2" ]
then
echo "at least 2 arguments are mandatory : file to search and pattern to search"
else
LOOK_FOR_FILE=$2
echo "Looking for files $LOOK_FOR_FILE"
fi
if [ -z "$3" ]
then
echo "looking in *.jar"
else
LOOK_IN_JAR=$3
echo "Looking in $LOOK_IN_JAR"
fi
if [ -z "$4" ]
then
echo "looking in ."
else
PLACE_IN=$4
echo "Looking in $PLACE_IN"
fi
for i in $(find $PLACE_IN -name "$LOOK_IN_JAR")
do
echo "Looking in jar $i ..."
unzip -p $i $LOOK_FOR_FILE | zgrep -i --text "$PATTERN"
if [ $? == 0 ]
then
echo -e "\n"
fi
done
Upvotes: 2