Spotlight Search by Full Path

findersearchspotlight

When performing a Spotlight search, either through the Finder or via terminal commands, is it possible to filter results against the full-path of a file, or at least the name of it's parent folder?

The reason I need to be able to filter by the full path is that although I'm searching for actual files, I only want to return files that are found within folders matching a particular pattern.

For example, consider I have a bunch of files structured like so:

Jobs
    Foo Poster
        Preview.jpg
        Final.psd
    Bar Poster
        Preview.png
        Final.psd
    Foo Banner
        Preview.jpg
        Final.psd

This is a bit of a contrived example for simplicity, but consider now that I want to find all the preview images found only within folders with "Poster" in the name.

I could do this with find using something like:

 find /path/to/Jobs -ipath *poster/preview*

However, what I'd really like is a way to do this using Spotlight, not only for speed but also for the additional search options available (labels, image sizes etc.).

Is it possible to do this? I know I can restrict searches to a single folder, but this is no use as what I really need is to find folders matching a pattern, and then search within those for the actual files.

I found the Document Container option in the Finder's search GUI, but this doesn't appear to work as I would expect; it sounds like it should let me match against a parent folder of a document, but this doesn't appear to be the case.

Assuming this isn't possible with the Finder's GUI directly (i.e- requires a Spotlight terminal command), I would ideally like to be able to create a smart folder if possible.

Best Answer

This is not possible with Spotlight alone. Spotlight does not index the file path as a property of the file. Thus it is not possible to use the path as search criterion.

You can use mdfind at the command line to search the Spotlight index. With the -onlyin parameter you can point it at the top of your folder hierarchy. You can the filter the returned results using grep.

mdfind -onlyin ~/Downloads/ 'kMDItemContentTypeTree == "public.image"cd' | grep '.*/test.*/.*'

If you need help building the query for mdfind, have a look at HoudahSpot. There you can set up your search criteria. Then go to Window > Raw Query to find the Spotlight query string you can use with mdfind.

While in HoudahSpot you can also use its ability to filter search results. Above the search results you will find a search field that allows for filter/exclude by name/path. Here you can use the asterisk as a wildcard.

Full disclosure: I am the developer of HoudahSpot.