Here is a trick that will help you find text within a file, when you don’t know what file contains that text. It uses the unix ‘find’ command, along with the ‘-exec’ option. The trick is to exec grep in a way that tells you the name of the file.

This way is insufficient, because it doesn’t tell you the filename:

find . -type f -exec grep mystring {} \;

The behavior of grep is to not display the filename when there is only one argument for the filename. Since the find command is actually running in a loop, the {} is only passing one argument for the filename. The trick is to pass an additional filename to the grep command, without affecting performance, so that grep will display the filename. The file to pass is /dev/null, as in the following example:

find . -type f -exec grep mystring {} /dev/null \;

Now you have two arguments for grep, so it will display not only the text that matched your search, but also the name of the file(s).

Leave a Reply

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