Using Grep To Search For Strings Within Files
While we would usually work in a ‘pretty’ editor such as Sublime Text there are often times we need to use the command line to track down a bug or make a small tweak. Grep is a powerful tool in our arsenal for searching within files from the command line.
In order to ease the pain of searching through potentially thousands of files to find a typo, for example, we can harness the power of Grep, a pattern matching engine. The following examples should help if you need to search within your codebase for certain strings, so let’s have a look.
First we’ll try to find a specific string of text, in any file, within the given directory.
$ grep -R "some text to find" directory/to/search directory/to/search/file1.xml: of text containing some text to find within a sentence directory/to/search/subdir/file2.php: different file with some text to find using grep directory/to/search/file3.php: "some text to find" directory/to/search/subdir2/file4.phtml: even finds some text to find in a subdirectory
As you can see, results are returned as a path, filename and snippet. If you prefer just to return filenames you can add -l
. Note the search path can be absolute or relative so your current directory doesn’t matter.
The above search is a great starter, but let’s say the string you need to find is pretty common. In these cases it is often useful to narrow the search parameters to just file types you are interested in, for example .php
to find a class or .phtml
to find something within a template. The following example shows how to do just that.
$ grep --include=\*.php -R "some text to find" directory/to/search directory/to/search/subdir/file2.php: different file with some text to find using grep directory/to/search/file3.php: "some text to find"
We can do even better if we need to though, as the --include
parameter can take a regex, so the following will search both .php
and .phtml
files.
$ grep --include=\*.{php,phtml} -R "some text to find" directory/to/search directory/to/search/subdir/file2.php: different file with some text to find using grep directory/to/search/file3.php: "some text to find" directory/to/search/subdir2/file4.phtml: even finds some text to find in a subdirectory
Finally one more useful option lets us exclude a directory, or directories, from the search. This is useful in cases where you need quite a broad search but can safely ignore a large number of files, such as your .git/
or vendor/
directories.
$ grep --exclude-dir={subdir,subdir2} --include=\*.{php,phtml} -R "some text to find" directory/to/search directory/to/search/file3.php: "some text to find"
Hopefully these command line tips will save you some time on your next project, and we’ll feature more soon.