Skip to content

Instantly share code, notes, and snippets.

@cpeisert
Created September 23, 2012 02:12
Show Gist options
  • Save cpeisert/3768561 to your computer and use it in GitHub Desktop.
Save cpeisert/3768561 to your computer and use it in GitHub Desktop.
Bash script to search Jar files. Each archived file is searched for the specified string.
#!/bin/bash
#Suggested file name: searchjars
if [[ $1 = "-h" || $1 = "--help" ]]
then
echo "Usage: $0 [STRING] [DIRECTORY]..."
echo "Search DIRECTORY(s) for Jar files. For each Jar, search the archived"
echo "files for STRING."
echo ""
echo "Default directory path is the current directory. Multiple directory "
echo "paths may be specified."
echo ""
echo "Example:"
echo " $0 ClassName /home/bsmith/java_project/lib"
exit 0
fi
args=("$@")
arg_count=${#args[@]}
if [ $arg_count -eq 0 ] ; then
echo "Missing STRING argument."
echo "Try \`$0 --help\` for more information."
exit 2
fi
findString=$1
declare -a dirs
if [ $arg_count -lt 2 ] ; then
dirs=( "`pwd`" )
else
for (( i=1;i<arg_count;i++)) ; do
dirs[$i - 1]=${args[${i}]}
done
fi
echo "Searching file \"$1\" in directory(s): ${dirs[@]/%/$','}" | sed 's/,\s*$//'
#
# Search for jar files in specified directory. For each jar file, search the
# archived files for findString.
#
# param $1 The directory to search.
#
function searchJarsInDir {
local dir="$1"
# See Stack Overflow question: http://stackoverflow.com/q/1116992/1164465
while IFS= read -r -d $'\0' file; do
filename=`unzip -l "$file" | cut -d: -f2 | cut -d" " -f4 | grep -i $findString`
if [ -n "$filename" ] ; then
echo "Found in $file"
for thefile in $filename; do
echo " –>" $thefile
done
fi
done < <(find "$dir" -name "*.jar" -print0)
}
for dir in "${dirs[@]}" ; do
searchJarsInDir "$dir"
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment