Finding Files by Content

Problem

How do you find a file of some known content? Let’s say that you had written an important letter and saved it as a text file, putting .txt on the end of the filename. Beyond that, the only thing you remember about the content of the letter is that you had used the word “portend.”

Solution

If you are in the vicinity of that file, say within the current directory, you can start with a simple grep:

grep -i portend *.txt

With the -i option, grep will ignore upper-and lowercase difference. This command may not be sufficient to find what you’re looking for, but start simply. Of course, if you think the file might be in one of your many subdirectories, you can try to reach all the files that are in subdirectories of the current directory with this command:

grep -i portend */*.txt

Let’s face it, though, that’s not a very thorough search.

If that doesn’t do it, let’s use a more complete solution: the find command. Use the -exec option on find so that if the predicates are true up to that point, it will execute a command for each file it finds. You can invoke grep or other utilities like this:

find . -name '*.txt' -exec grep -Hi portend '{}' \;

Discussion

We use the -name '*.txt' construct to help narrow down the search. Any such test will help, since having to run a separate executable for each file that it finds is costly in time and CPU horsepower. Maybe you have a rough idea of how old the file is (e.g., -mdate -5 or some such).

The '{}' is where the filename is put ...

Get bash Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.