Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How use grep to search in all subdirectories 4

Status
Not open for further replies.

YerMom

Programmer
Oct 3, 2006
127
0
0
US
I need to search for a string in all subdirectories of the current directory I'm in.

For example, I might want to find all files that contain the word "import". I thought the following would work, but it does not:

Code:
grep import */*

The man pages for grep don't seem to help.

Thanks...


 
You could try something like:

for file in `find $PWD -print`
do
grep -l import $file
done

(NB: that is 'minus el')

I hope that helps

Mike
 
Very nice Mike -- works fine!

How would I modify the script to accept directory as a command line parameter instead of using the $PWD?

Thanks,
Steve
 
Hi there,

or do it like this: ;-)


find ./ -type f -exec grep -l searchterm {} \;


At least this works under AIX ...

Regards
Thomas
 
GNU versions of grep have this flag
[tt] -R, -r, --recursive equivalent to --directories=recurse[/tt]

--
If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
 
Thanks everyone for helping.

The version I have does not have the -R or -r flags.

Thomas, I tried your solution and it works, but after the command runs, it creates a file called {} in the directory where I started the search. I'm assuming that the {} in the command did this. What is {} for?

Thanks,
Steve
 
What is {} for?
man find

Hope This Helps, PH.
FAQ219-2884
FAQ181-2886
 
Hi YerMom,

You asked:
"How would I modify the script to accept directory as a command line parameter instead of using the $PWD?"

Something like:
Code:
   search_dir=$1
   if [[ -z ${search_dir} ]]
   then
       echo "Enter search directory [$PWD]: \c"
       read search_dir
       if [[ -z ${search_dir} ]]; then search_dir=$PWD; fi
   fi
   for file in `find ${search_dir} -print`
   do
     grep -l import $file
   done

I hope that helps

Mike
 
Mike,

Yes that helps. Nice job. (I see you are one of those Unix masters.)

Steve
 
Thanks for the 'star' (and the flattery). Let's just say I know a bit.

Regards.

Mike
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top