Finding files that Spotlight is missing

I generally use Spotlight when searching my Mac for a file, but there are times it doesn't work, especially when I'm trying to find a file that contains a phrase I know. For instance, I may have a file named "Fred.txt", and it contains the phrase "foo bar", but when I open Spotlight and type in "foo bar", the file Fred.txt never shows up.

When this happens, and I know that phrase is in a file somewhere, I turn to the Terminal and the Unix find command. To solve this problem -- finding a file by knowing a string it contains -- I always use this command:

find ~ -type f -exec grep -il 'foo bar' {} \;

This syntax may seem a little wonky, as it's a complicated command, but here's what it means:

  • find ~ means "use the find command, and start looking in my home directory (represented by the tilde character)"
  • -type f means "only look for text files, don't worry about directories"
  • -exec grep -il 'foo bar' means "use the grep command to search all text files for the string 'foo bar'; do it in a case-insensitive manner; and just print the name of the file when it's found"
  • {} \; ... well, it's hard to say exactly what that means, but I like to think of it as a placeholder. I think of this as where the find command stores all the filenames it finds, and then runs them through the grep command.

If the file exists, this command will find it (no pun intended). It may take a little while, as this command works interactively, working as fast as it can to look through every file in your home directory, and anywhere beneath your home directory. When it finds the file it will print out the full path to the file's location.

One more note: if the file is found pretty early, but this command keeps on running, just hit [Ctrl][C] to stop it.

While I'm in the neighborhood, if the name grep sounds where, it's because it's an acronym, and means "general regular expression parser", or something like that. If you don't like that name, just think of it as meaning "search", or more specifically "search for the string (or pattern) I tell you to look for".