brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: mdfind with a kMDItem query finds files by metadata, not by name

Terminal
~/tips/tip-macos-mdfind-kmditem-query

mdfind -onlyin ~/Documents "kMDItemContentType == 'com.adobe.pdf'"

Finds files by one metadata field, such as content type or author, from Terminal.

A plain mdfind search matches any metadata that contains your word. When I want one specific property, such as the file type or the author, a query expression is more precise.

mdfind accepts a query expression: an attribute name, a comparison and a value in quotes. Attribute names start with kMDItem. This one finds every PDF in Documents by its content type:

mdfind -onlyin ~/Documents "kMDItemContentType == 'com.adobe.pdf'"

The man page shows the same pattern for authors, with * as a wildcard: mdfind "kMDItemAuthors == '*Jansen*'" lists files whose author field contains that name. Add -count when you only want the number of matches, not the list.

Which attributes exist? The man page points to mdimport -X, which prints the schema. For one file, mdls shows the attributes and values it actually has, which is the easiest way to find the right name before you write a query.

The caveat is quoting. The whole expression goes in double quotes for the shell and the value in single quotes inside it; get that wrong and you get an error or zero results. Also, not every file has every attribute. A PDF saved by some apps has no author at all, so an empty result can mean the field is empty, not that the file isn’t there.

Further reading: mdfind.1 man page, mdimport.1 man page

More Terminal tips ioreg -rn AppleSmartBattery | grep CycleCount Terminal can save your windows and tabs as a window group Export a Terminal profile to a .terminal file and import it on another Mac mc hidutil property --set '{"UserKeyMapping":[{"HIDKeyboardModifierMappingSrc":0x700000039,"HIDKeyboardModifierMappingDst":0x700000029}]}' All Terminal tips (116) All topics

Link