Home » Questions » Computers [ Ask a new question ]

How to Combine find and grep for a complex search? ( GNU/linux, find, grep )

How to Combine find and grep for a complex search? ( GNU/linux, find, grep )

I'm trying to do a text search in some files that share a similar directory structure, but are not in the same directory tree, in GNU/Linux.

Asked by: Guest | Views: 314
Total answers/comments: 2
bert [Entry]

"Try

find /srv/www/*/htdocs/system/application/ -name ""*.php"" -exec grep ""debug ("" {} \; -print

This should recursively search the folders under application for files with .php extension and pass them to grep.

An optimization on this would be to execute:

find /srv/www/*/htdocs/system/application/ -name ""*.php"" -print0 | xargs -0 grep -H ""debug (""

This uses xargs to pass all the .php files output by find as arguments to a single grep command;
e.g., grep ""debug ("" file1 file2 file3. The -print0 option of find and -0 option of xargs ensure the spaces in file and directory names are correctly handled. The -H option passed to grep ensures that the filename is printed in all situations. (By default, grep prints the filename only when multiple arguments are passed in.)

From man xargs:

-0Input items are terminated by a null character instead of by whitespace, and the quotes and backslash
are not special (every character is taken literally).  Disables the end of file string, which is
treated like any other argument.  Useful when input items might contain white space, quote marks, or
backslashes.  The GNU find -print0 option produces input suitable for this mode."
bert [Entry]

"Your shell can find the php files and give them to grep. In bash:

shopt -s nullglob globstar
grep searchterm /srv/www/*/htdocs/system/application/**/*.php"