Operating System - HP-UX
1833059 Members
2585 Online
110049 Solutions
New Discussion

Re: Find text throughout all files in a directory structure

 
Joan Blais
Frequent Advisor

Find text throughout all files in a directory structure

How can I do a search of all file contents, for a specific text, in an entire directory structure?
7 REPLIES 7
Pete Randall
Outstanding Contributor

Re: Find text throughout all files in a directory structure

Try this:

find /startdir -type f -exec grep -l 'text string to search for' {} \;


Pete

Pete
A. Clay Stephenson
Acclaimed Contributor

Re: Find text throughout all files in a directory structure

You can leverage the find command and then apply grep BUT you must make certain that you are only examining text files. Thus the "file" command should also be used. Create a shell script, find.sh:

#!/usr/bin/sh

TARGET=${1} # string to look for
shift
find . -type f | while read FNAME
do
file "${FNAME}" | grep -q -i "text"
STAT=${?}
if [[ ${STAT} -eq 0 ]]
then # is a text file of some kind
grep -q "${TARGET}" "${FNAME}"
STAT=${?}
if [[ ${STAT} -eq 0 ]]
then # match found
echo "File: ${FNAME}"
grep "${TARGET}" "${FNAME}"
fi
fi
done
--------------------------------

Use it like this:

cd to desired starting directory.
find.sh "String to look for"
If it ain't broke, I can fix that.
Eknath
Trusted Contributor

Re: Find text throughout all files in a directory structure

Hi Joan

Here is the abstract of man find
Search the two directories /example and /new/example for files containing the string "Where are you" and print the names of the files:
#find /example /new/example -exec grep -l 'Where are you' {} \;

Refer man pages for more details
#man find

Cheers!!!
eknath
A. Clay Stephenson
Acclaimed Contributor

Re: Find text throughout all files in a directory structure

Danger, Will Robinson. Grep is only designed to handle text files; simply passing the output of find to grep can cause unpredictable results unless you know that only text files are going to be processed. The smarter, safer, if more complicated play is to first use the "file" command to examine the file and report it to be "text". Then pass the filename onto grep for the pattern match.
If it ain't broke, I can fix that.
Cem Tugrul
Esteemed Contributor

Re: Find text throughout all files in a directory structure

Hi,
i am fully agree with A.Clay and you can
use "grep" command with options -l -i ...
to search a pattern for regular file
so also Pete's reply is significant as he
uses "-type f"

Good Luck,
Our greatest duty in this life is to help others. And please, if you can't
Muthukumar_5
Honored Contributor

Re: Find text throughout all files in a directory structure

You can do it as,

find -type f | xargs grep 'text'

hth.
Easy to suggest when don't know about the problem!
Joan Blais
Frequent Advisor

Re: Find text throughout all files in a directory structure

Thank you all for your help.\-Joan