In OS X, you can use search for files in the command line using mdfind.

Basic usage

Use mdfind to search for anything like you would in spotlight:

1
mdfind searchTerm

For example mdfind robocop will search for any file which contains the term robocop and return a list of paths. Just like spotlight, it will also search inside text documents, pdf documents, emails and so on.

Additional parameters

  • use -count to return the number of results instead of a list of files: mdfind robocop -count
  • use -live to watch an live-update the list of results: mdfind robocop -live
  • use -onlyin <directory> to search in a specific path: mdfind robocop -onlyin ~/Music
  • use -name <name> to limit the search to filenames (won’t search inside files for example): mdfind -name robocop

Advanced search queries using OS X Files Metadata

Check files metadata

You can read a file’s metadata using the mdls command.

For example:

1
mdls ~/Pictures/Birthday.jpg

Will print out a list of attributes and their values, something like:

1
2
3
4
5
_kMDItemOwnerUserID = 501
kMDItemContentCreationDate = 2015-12-17 05:32:42 +0000
kMDItemContentModificationDate = 2015-12-17 05:32:42 +0000
kMDItemContentType = "dyn.ah62d4rv4ge80w6dp"
[...]

Search files by metadata attributes

You can build more advanced queries and perform complex searches by using these metadata attributes using

1
mdfind query

For example:

Search for files whose type contains MPEG:

1
mdfind "kMDItemKind == '*MPEG*'"

Search for image files with a width > 3000 pixels:

1
mdfind "kMDItemPixelWidth > 3000"

Search for audio and movie files with a duration < 2 minutes:

1
mdfind "kMDItemDurationSeconds < 120"