Terminal 101: Advanced Command Line Searching with Boolean Operators
Posted 10/01/2012 at 11:00am
| by Cory Bohon
Every Monday, we'll show you how to do something new and simple with Apple's built-in command line application. You don't need any fancy software, or a knowledge of coding to do any of these. All you need is a keyboard to type 'em out!
Last week, we covered the basics of using mdfind to locate files on your Mac using the metadata stored within the files. This week, we’re going to take that to another level by showing you how to use boolean operators and filters to refine the search results to point to only the files you wish to locate. Continue reading to learn more about unleashing the power of mdfind.
Using Boolean Operators
When passing multiple keywords to the mdfind command, the mdfind command assumes that you wish to search for files that contain all of the elements within (a logical AND). However, you can add additional operators to this search string to refine the results even more:
The pipe character (|) means a Boolean OR (find files matching any of the terms listed), and can be used like this:
mdfind "maclife | terminal"
The above command will find files that have “maclife” or “terminal” or both commands listed.
The dash (-) character means to exclude a specified term from the search results. So, using this command would look like this:
mdfind "maclife (-terminal)"
Here, the command will find files that have the word “maclife,” but exclude results have have the word “terminal.”

You can take this a bit further, however, with groups. By creating a group, you have more power over how the boolean operators work. Groups are created by using parenthesis like this:
mdfind "(terminal | cory) maclife"
This command will find files with either “terminal AND maclife” OR “cory AND maclife”. As you can see, the level of refinement is virtually unlimited with groups and the AND, OR, and Exclude operators.
Only In

Sometimes you wish to only search for files in a certain directory. When you wish to do this, give the -onlyin option a try:
mdfind -onlyin ~/Documents maclife
This command will find files matching “maclife” in the directory “~/Documents”.
Refining Searches with Filters

Filters are a great way to narrow down your search results. We’ll filter the results by piping the results through the grep command, like this:
mdfind maclife | grep -v IMAP
The above command will do the basic search for the search term “maclife,” but will omit outputting any result to the screen that has IMAP as the filename. This will filter out those results from your Mail accounts. You can replace “IMAP” with any file extension to filter it out of the results.
Cory Bohon is a freelance technology writer, indie Mac and iOS developer, and amateur photographer. Follow this article's author, Cory Bohon on Twitter.