Tuesday, 3 March 2009

Unix shell script 1

The following script finds a given string in the files in given directory. The directory is passed as an argument and it has to be relative path from the users home directory.

#!/bin/csh

if( !( -d ~/$1 ) ) then
echo No directory supplied
exit
endif

echo Enter string:
set w = $<

foreach a ( `ls ~/$1` )
if( !( -d $a ) ) then
set s = `grep -s $w ~/$1/$a | wc -l`

if ( $s>0 ) then
echo $a : $w found
else
echo $a : $w not found
endif
endif
end


As a result we get listing of all files, saying in which the given string has been found and in which has not.

1 comment:

  1. Nice one. A bash one using grep -q

    $ strng="bash"
    $ find /home/jsaikia/work/ -maxdepth 1 -type f | while read file
    > do
    > grep -q $strng $file
    > [ $? -eq 0 ] && echo "$file: string $strng found" || echo "$file: string $strng not found"
    > done

    ReplyDelete