I am searching for a class declaration on a site with hundreds of PHP files. How can I do this in the current folder and subfolders using grep?

I tested cding to the folder and then something like

grep -r 'class MyClass' *.php
link|improve this question
When this migrates to superuser, you might want to say something about what you wanted that grep -r didn't give you. – Jerry Coffin Jan 19 '10 at 16:45
I'm confused - didn't you just answer yourself? what were the results of that line? are you trying to further optimize it? please envision reading this question as someone else, because it's confusing and unclear. – meder Jan 19 '10 at 16:46
@other comments: His grep -r statement isn't giving what he wants, unless all the folders end with .php which is probably not the case... – David Oneill Jan 19 '10 at 16:47
I didn't get anything at all. I assume it didn't work because I know it finds it when im on the folder which has the file with this class – Sam3k Jan 19 '10 at 17:48
I found the file by luck. When searching for the file in the folder that has the PHP file with that line, it finds it (no need for -r). If I CD to the root and do the search with recursion -r it doesn't return anything. – Sam3k Jan 19 '10 at 17:50
feedback

migrated from stackoverflow.com Jan 19 '10 at 19:13

This question came from our site for professional and enthusiast programmers.

5 Answers

I'd recommend that you use something like ctags rather than do it with a grep. However, if you want to, you can do something like

 find <top level dir> -name \*.php | xargs grep "class MyClass"

This of course assumes that you have just a single space between class and myClass which might not be true. It's easy to change the regexp to look for any number of whitespaces though.

link|improve this answer
feedback

If you use -r, you probably want to just search the current directory:

grep -r 'class MyClass' .

Note the period on the end of the above.

What you told grep was that you wanted it to recursively search every *.php file or directory, which likely didn't include any directories.

But, if you ever have more than one space after class, you might want to allow more characters:

grep -r 'class *MyClass' .
link|improve this answer
feedback
grep -r 'class MyClass' *.php

will search through all the folders with names ending with .php

grep -r 'class MyClass' . | grep .php

will search for class MyClass in all files in all sub folders, then only return the ones that have .php in them.

link|improve this answer
feedback

find . -type f -name *.php -print -exec grep \"class MyClass\" {} \; will give you the contents of the line its found on as well as the path to the file.

link|improve this answer
feedback

Using the ever wonderful ack,

ack --php 'class MyClass'
link|improve this answer
feedback

Your Answer

 
or
required, but never shown