OSXFAQ Mac OS X UNIX Tip-of-the-Day
Spotlight - Boolean Expressions
Yesterday, we saw how to use mdfind to find files that contain particular text, or have particular metadata. Today we'll look at how we can be more exacting about what words a file should, or should not, contain.
To illustrate, we have three simple text files:
$ cat file1.txt
Kiss me
$ cat file2.txt
Kate
$ cat file3.txt
Kiss me, kate
Let's look for files that contain the word "kiss":
$ mdfind -onlyin ~/splotlight-test "kiss"
/Users/saruman/splotlight-test/file1.txt
/Users/saruman/splotlight-test/file3.txt
Note use of the option -onlyin to limit searches to files rooted in a particular directory hierarchy. You must specify the full path name of the directory.
And files that contain the word "kate":
$ mdfind -onlyin ~/splotlight-test "kate"
/Users/saruman/splotlight-test/file2.txt
/Users/saruman/splotlight-test/file3.txt
If we specify both terms, Spotlight will return those files that contain ALL the terms - in this example "kiss" AND "kate".
$ mdfind -onlyin ~/splotlight-test "kiss kate"
/Users/saruman/splotlight-test/file3.txt
To test for "kiss" OR "kate", we separate the terms with '|'.
$ mdfind -onlyin ~/splotlight-test "kiss|kate"
/Users/saruman/splotlight-test/file1.txt
/Users/saruman/splotlight-test/file2.txt
/Users/saruman/splotlight-test/file3.txt
There must be no white space around the '|' symbol.
What about not kissing kate?
$ mdfind -onlyin ~/splotlight-test "kiss(-kate)"
/Users/saruman/splotlight-test/file1.txt
Again, make sure there is no white space between the terms.
And finally, "kiss" or "kate", but not "me".
$ mdfind -onlyin ~/splotlight-test "kiss|kate(-me)"
/Users/saruman/splotlight-test/file2.txt
Tomorrow, we'll combine mdfind with regular Unix commands such as find, grep, and xargs.
|