在JAR内的文件内搜索

时间:2012-03-22 23:08:59

标签: bash search jar terminal grep

我找到了很多关于如何搜索jar中存在的文件的例子,但我想找到存在于jar中的文件中的文本。如何在不解压缩所有jar文件的情况下执行此操作?

#!/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

2 个答案:

答案 0 :(得分:4)

如果您只想查看jar中的任何文件是否包含特定字符串($LOOK_FOR),但不关心哪个文件,可以使用unzip执行此操作,这里是一个小小的考验:

$ 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

使用-p选项,文件将解压缩为pipe(stdout)。

如果您想知道字符串在哪个文件中,我认为您不能做任何比解包更好的事情。

答案 1 :(得分:2)

这几乎是一样的,但添加了一些参数,并且grep返回给出了整行。我用它来控制很多罐子中的一些属性,或者任何相关的文本。

#!/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
相关问题