Can "mdfind" search for phrases and not just unordered words?

Is there a way to search for an exact phrase using the mdfind utility? For example, I created two text documents titled "test1" and "test2". The contents of "test1" are:

I love Apple

And the contents of "test2" are:

Apple love I

When I type this in terminal (I placed both files in ~/Documents):

mdfind "I love Apple" -onlyin ~/Documents

I get:

~/Documents/test1.txt
~/Documents/test2.txt

How would I search for the exact phrase "I love Apple" so mdfind only returns results containing those words in that order (in this case only "test1.txt")?


You need to escape your quotes like so:

mdfind \"I love Apple\" -onlyin ~/Documents

This results in just the one document being found:

~/Documents/test1.txt

Without escaping them, I don't think the quotes actually get passed to the mdfind command, they're just interpreted by your shell to say that I love Apple is a single argument. With the backslash-escaping, the argument then includes the quote characters.


The double quotes can also be placed inside single quotes:

mdfind '"exact phrase"'

This would search only in the contents:

mdfind 'kMDItemTextContent=="*exact phrase*"'