How can I find an exact string in file contents across many folders from the command line on macOS?
I tried all the recipes (double quotes, escaped double quotes etc.) in vain. I'm not interested in files containing any or all of these words, only the exact string. (EasyFind does the job.) I'm using macOS Catalina with zsh.
Is there a way to have mdfind detect an exact string, say "what I look for", in the content of files?
It might be easier to use tools dedictated for searching text within files, e.g. grep
(part of macOS) or ag
(brew install ag
):
fgrep -r "Text to match" PATH
ag -F "Text to match" PATH
Spotlight allows this and is my favored tool, despite how painful it is to learn how to do this from Apple's documentation alone. The man page for mdfind is almost criminally negligent for not mentioning how to search for a string, but I shall not rant too much more on that here.
mdfind 'kMDItemTextContent = "this exact string"'
Pay attention to the double quote and single quote and also, when you are looking for help online - if the article mentions NSPredicate or that spotlight uses two different languages, you are on to the good stuff. If the article says "x can't be done" consider that perhaps "The author hasn't needed to learn how to do x, yet".
Here are some great places to start with predicates - the log man page, excellent programming references like https://nshipster.com which glosses over how hard "natural language" search expressions are - especially when you mix pcre/regex with SQL baggage.
NSPredicate is a Foundation class that specifies how data should be fetched or filtered. Its query language, which is like a cross between a SQL WHERE clause and a regular expression, provides an expressive, natural language interface to define logical conditions on which a collection is searched.
- https://stackoverflow.com/questions/30271328/how-do-i-get-mdfind-to-include-folder-matches-in-addition-to-files
- https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/Predicates/Articles/pSpotlightComparison.html#//apple_ref/doc/uid/TP40002370-SW1
Basically, for reasons, spotlight can be very hard on newcomers, very confusing syntactically, but mostly gets it right for some easy things and finding a string in a file is more challenging than you might expect. The system was designed by programmers and then a second language was patched on and there's a lot of easy to search information that's just wrong or incomplete.
Thankfully there are some great explanations how to learn this powerful tool.
- https://www.macworld.com/article/3264653/macos-how-to-use-spotlights-query-language-to-create-an-all-my-files-like-feature.html (Glenn writes very well)
- https://support.apple.com/en-am/guide/mac-help/mh15155/mac (Narrowing your search help)