Script search.sh

From campisano.org
Jump to navigation Jump to search
#!/bin/sh
#
# search.sh
# v 1.1
#



echo
echo cerca una stringa nei file contenuti nella cartella specificata:
echo se non e\' stato specificato nessuna cartella,
echo cerca nella cartella attuale;
echo se il primo parametro passato e\' -R, fa una ricerca in tutte le sottodirectory;
echo



#--- E' stato inserita almeno la STRING da cercare? ---#
if test -z "$1"; then
    echo    Usage: $0 " [-R] [DIRECTORY] <STRING>"
    echo    Usage: $0 " <STRING>"
    exit -1;
fi;



OPT="";
DIR="";
STR="";

# cerco di interpretare la volonta' dell'utente
if test "$1" = "-R"; then  # se l'opzione -R e' specificata
    OPT=$1;

    if [ -n "$3" ]; then   # se esiste il terzo parametro, il secondo e' la directory
        DIR=$2;
        STR=$3;
    else                   # altrimenti il secondo e' la stringa
        DIR=".";
        STR=$2;
    fi;
else                       # altrimenti se non e' stata specificata -R

    if [ -n "$2" ]; then   # se esiste il secondo parametro, il primo e' la directory
        DIR=$1;
        STR=$2;
    else                   # altrimenti il primo e' la stringa
        DIR=".";
        STR=$1;
    fi;
fi;



echo "opt: $OPT";
echo "dir: $DIR";
echo "str: $STR";
sleep 1s;



searchfn() {
    OPTfn=$1;
    DIRfn=$2;
    STRfn=$3;

    # eseguo il comando che ritengo volesse l'utente
    for FILE in $DIRfn/* $DIRfn/.[!.]*; do

        if test -f "$FILE"; then
            OUTfn=`cat -n "$FILE" | grep -i "$STRfn"`;

            if test "$OUTfn" != ""; then
                echo "file: $FILE";
                echo "$OUTfn";
                echo;
            fi;
        elif test -d "$FILE"; then

            if test "$OPTfn" = "-R"; then
                searchfn "$OPT" "$FILE" "$STR";
            fi;
        fi;
    done;
}



searchfn "$OPT" "$DIR" "$STR";



exit 0;



# End