Sometimes, when I’m in a big directory full of files for a project, I discover that I can’t remember where a particular function is originally defined.  In those cases, I use the following command to search through files and print out the filenames where my search criteria is located:

find ./ -name \*.php -exec grep -H 'function insert_data' {} \;

What’s going on

The first part of the command find ./ -name \*.php tells the machine that we want to find all files in the current directory that have the extension php.  The -name argument expects a pattern, and we use the \ to escape the wildcard so that the OS doesn’t throw an error and instead looks for all files that match the pattern of a .php extension.  The second option the -exec command, tells find that we want it to execute a particular command, in our case, grep.  In other words, once you’ve found files that match the pattern, do a grep on the contents.  In the grep command, the -H flag tells it that we want the whole file name and then we give it the search pattern we are looking for (e.g. ‘function insert_data’).  The final part of the command (the {} \; ) rounds out the find command.  This is an extension of the -exec command and tells find that we want the current file name being processed to be substituted into the grep command so that the grep pattern can be found in that file.  The \; just escapes the termination of the -exec command.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.