Re-posted from Command Line Kung Fu blog here. Check out the link on how to search on other platforms too!
While it’s great to have 3 or 4 commands to string together to get the output you want (heck, this is part of the joy of the power of ‘nix, the freedom to do almost anything because you’re not restricted to a specific command), sometimes it’s nice to have one command that will do it for you, out of the box.
Enter Spotlight on the Mac. Spotlight is Apple’s built in OS-level search that functions on meta tags and even though everyone rags on them for the GUI, Apple usually puts in a command-line function or two for our trouble.
$ mdfind evil
The above command will search file names and file contents for the string “evil”. Simple enough right?
$ mdfind evil -onlyin /Users/ed
Still pretty simple, this will limit the search for “evil” in Ed’s home directory. I’m sure we won’t find anything, right Ed?
So back to the original challenge, what good would this be unless it can search for file type? Guess what, you can!
$ mdfind "evil kind:text" -onlyin /Users/ed
This will find all text files in Ed’s home directory with the string “evil”. Wonder what that’ll come up with…
You can use kind for other things too, Applications, Contacts, Folders, etc.
This is only a very simple Spotlight search. You can go much further. Everything in OS X (10.4 and above) has meta tags that detail all sorts of interesting things about the files. Run the following to find out just what kind of data that Spotlight sees:
$ mdls "/Users/ed/Desktop/March CLK Fu.txt" kMDItemContentCreationDate = 2010-02-09 17:54:00 -0500 kMDItemContentModificationDate = 2010-02-09 17:54:00 -0500 kMDItemContentType = "public.plain-text" kMDItemContentTypeTree = ( "public.plain-text", "public.text", "public.data", "public.item", "public.content" ) kMDItemDisplayName = "March CLK Fu.txt" kMDItemFSContentChangeDate = 2010-02-09 17:54:00 -0500 kMDItemFSCreationDate = 2010-02-09 17:54:00 -0500 kMDItemFSCreatorCode = "" kMDItemFSFinderFlags = 0 kMDItemFSHasCustomIcon = 0 kMDItemFSInvisible = 0 kMDItemFSIsExtensionHidden = 0 kMDItemFSIsStationery = 0 kMDItemFSLabel = 0 kMDItemFSName = "March CLK Fu.txt" kMDItemFSNodeCount = 0 kMDItemFSOwnerGroupID = 501 kMDItemFSOwnerUserID = 501 kMDItemFSSize = 3 kMDItemFSTypeCode = "" kMDItemKind = "Plain text" kMDItemLastUsedDate = 2010-02-09 17:54:00 -0500 kMDItemUsedDates = ( 2010-02-09 00:00:00 -0500 )
All fun things you can search by! For example:
$ mdfind "kMDItemFSOwnerGroupID == '501'"
Will get everything owned by UID 501 (usually the first created user on the system).
Note: It should be mentioned that most of the ‘nix command line fu on this site will work on a Mac, it is after all BSD under the hood. That being said, sometimes we can save some time with the built in utilities, like Spotlight.