10.4: Access Spotlight saved searches via the Terminal

May 02, '05 10:31:00AM

Contributed by: mithras

Tiger only hintTiger's new "Saved Search Folders" are convenient in the Finder. But what if you want to access search results from the command line, without retyping the entire search with mdfind? I've written two Perl scripts to help do just that, made possible by the fact that a .savedSearch file is just an XML file containing your search criteria.

spotlightls (view source) works just like the regular ls, except that it will scan the parameters you feed it, and expand any .savedSearch file to the results of that search.

cache_search_results (view source) will look in ~/Library/Saved Searches/ for .savedSearch files. For each one it finds, it will create a directory of the same name (without the '.savedSearch'), and fill it with symlinks to the results of the search.

Read on for examples of both...

Here's spotlightls (linebreaks added for a narrower display):

$ spotlightls -l NewPDFs.savedSearch
 -rw------- 1 mithras wheel 9002 Apr 21 11:32 /Users/mithras/.Trash/
   Web Receipts/Untitled.pdf
 -rw-r--r-- 1 mithras wheel 225031 Apr 22 12:28 /Users/mithras/
   Documents/alon_liebler_199.pdf
And of cache_saved_searches (linebreaks added for a narrower display):
$ cache_saved_searches
Caching NewPDFs.savedSearch...
        j.0029-4624.2005.00492.x-1.pdf
        j.0029-4624.2005.00492.x.pdf
        science.pdf
$ spotlightls -l NewPDFs/
total 112
lrwxr-xr-x   1 mithras  wheel   45 Apr 24 16:32 Untitled.pdf -> 
  /Users/mithras/.Trash/Web Receipts/Untitled.pdf
lrwxr-xr-x   1 mithras  wheel   86 Apr 24 16:32 alon_liebler_199.pdf -> 
  /Users/mithras/Documents/alon_liebler_199.pdf
To use these scripts:
  1. Save the text of the script into a file with the name you want (obviously, I suggest spotlightls and cache_saved_searches, but anything will do).
  2. Put the files somewhere appropriate, e.g. ~/bin -- that folder should be in your path; add export PATH="$HOME/bin:$PATH" to your .bashrc
  3. Make them executable with chmod a+x scriptname
  4. If you want spotlightls to replace your regular ls, add this to your .bashrc: alias ls="spotlightls"
[robg adds: I haven't tested these scripts...]

Comments (2)


Mac OS X Hints
http://hints.macworld.com/article.php?story=20050424164321350