Operating System - Linux
1754339 Members
2557 Online
108813 Solutions
New Discussion юеВ

Re: Need help with a script

 
SOLVED
Go to solution
S-un-B-ix-S
Advisor

Need help with a script

I need a script that search only text files for any occurrence for a certain word, and then will send the following information to a separate log file: the full path of the file.

could anyone help?
5 REPLIES 5
James R. Ferguson
Acclaimed Contributor
Solution

Re: Need help with a script

Hi:

Here's a Perl script that recursively finds all *text* (not binary) files in the current directory and reports case-insensitive matches to the pattern passed as an argument :

# perl -MFile::Find -we 'find(sub{push @f,$File::Find::name if -f $_ && -T _},".");@a=`grep -i $ARGV[0] @f`;print for sort @a'

Regards!

...JRF...
A. Clay Stephenson
Acclaimed Contributor

Re: Need help with a script

Something like this should be close:
------------------------------------
#!/usr/bin/sh

typeset PROG=${0}
if [[ ${#} -lt 1 ]]
then
echo "Usage: ${PROG} target_string" >&2
exit 255
fi
typeset TARGET=${1}
shift

typeset FNAME=""
typeset -i GSTAT=0


find . -type f -print | while read FNAME
do
file "${FNAME}" | grep -q -i "ascii"
GSTAT=${?}
if [[ ${GSTAT} -eq 0 ]]
then # it's a text file
grep -q "${TARGET}" "${FNAME}"
GSTAT=${?}
if [[ ${GSTAT} -eq 0 ]]
then
echo "${NAME}"
fi
fi
done
exit 0
-------------------------------

Use it like this:

cd to desired starting directory
findit.sh "my target string" > mylist

It leverages the file command which includes "ascii" in its output of anything that is a text file. Those files are then examined with grep (-q -- quiet; we only care if a terget string is found or not; if found grep sets its exit code to 0).

Another aproach would be to use Perl's Find::File module and use the -T test to determine if a file is a text file.
If it ain't broke, I can fix that.
James R. Ferguson
Acclaimed Contributor

Re: Need help with a script

Hi (again):

Ooops; a slight correction to retain the order of matched lines while still sorting the filenames output:

# perl -MFile::Find -e 'find(sub{push @f,$File::Find::name if -f $_ && -T _},".");@a=sort @a;@a=`grep -i $ARGV[0] @f`;print @a' string_to_match

Regards!

...JRF...
James R. Ferguson
Acclaimed Contributor

Re: Need help with a script

Hi (again):

CRIPES!

... @f=sort @f ...

This is the REAL correction to retain the order of matched lines while still sorting the filenames output:

# perl -MFile::Find -e 'find(sub{push @f,$File::Find::name if -f $_ && -T _},".");@f=sort @f;@a=`grep -i $ARGV[0] @f`;print @a' string_to_match

Regards!

...JRF...
Ivan Ferreira
Honored Contributor

Re: Need help with a script

Example 1:
find / -type f -exec grep -l {} \; > /tmp/logfile

Example 2:
find / -type f -name *.txt -exec grep -l {} \; > /tmp/logfile
Por que hacerlo dificil si es posible hacerlo facil? - Why do it the hard way, when you can do it the easy way?