Wednesday, July 25, 2012

Search files within a ZIP archive using zipgrep tool

Bash script that search files within a ZIP archive for lines matching given string or pattern using zipgrep tool.

#!/bin/sh
# zipgrep Util 0.1
# Result ziprep by directory file
# @Jorge Iglesias

# Note: root users
if [ "$(whoami)" != 'root' ]; then
    echo "You have no permission to run $0 as non-root user"
        exit 1;
fi

clear
echo "zipgrep Util 0.1"
echo "Jorge Iglesias"
echo "----------------"

echo "Input pattern"
printf "> "
read pattern

echo "Input directory grep"
printf "> "
read directory

echo "Input directory output results"
printf "> "
read directoryOut

# Control will enter here if $DIRECTORY doesn't exist.
if [ ! -d "$directoryOut" ]; then
    mkdir $directoryOut
fi

cd $directory


index=0

for file in `dir -d *` ; do
    index=$((index+1))
    zipgrep $pattern $file > $directoryOut/$file.out
    # Control file size and delete files with size 0
    fileSize=$(stat -c "%s" $directoryOut/$file.out)
    if [ $fileSize = 0 ]; then {
        index=$((index-1))
        rm $directoryOut/$file.out
    }
    fi
done

echo "Pattern found in $index files."

No comments:

Post a Comment