10.4: A c-shell alias for searching via Spotlight

Mar 30, '06 05:41:00AM

Contributed by: mingo

Tiger only hintThis hint is motivated by this earlier hint, and other stuff I've read elsewhere. I created a csh alias to search via Spotlight. Results are returned in chronological order and logically grouped.

Here is a detailed description of the construction of the alias, so that readers can modify it to suit their own needs. The alias has five parts connected by four pipes. To reassemble the alias, put the five parts on a single line and add it to your .cshrc file.

As a summary, here's how it works. If one types:

 $ spot xanadu 
mdfind is asked to find all files in the current directory containing xanadu in their metadata. The output is piped to ls -lt, to sort it into chronological order (most recent at the top). The result of this is then piped to sed for tidying. Read on for the details...

Line 1:

 alias spot 'mdfind -onlyin "`pwd`" \!* |
This takes the argument of spot, xanadu in the example, and presents it to mdfind with the restriction of searching in the current directory.

Line 2:
 sed s/^.\*\$/\"\&\"/g | 
mdfind returns full path names for the files, without escaping any spaces or other special characters. sed will wrap the full path name in quotes (" ") to protect special characters from the shell.

Line 3:
 xargs ls -lt |
xargs takes the wrapped path names and passes them to ls -lt, which will then sort them in chronological order.

Line 4:
 sed  s:"`pwd`"/:: |
sed will remove from the path name the part from root up to the current directory. The assumption being that the user already knows what directory she|he is in.

Line 5:
 sed "s/^[-dltrwx]*\ *[0-9]*\ [a-z]*\ *[a-z]*\ *[0-9]*//"'
Finally, sed will remove the output of ls -lt from the beginning of the line, up to the modification date of the file. Note that the last part has four escaped spaces.

Here is the alias as a single line:

alias spot 'mdfind -onlyin "`pwd`" \!* | sed s/^.\*\$/\"\&\"/g | xargs ls -lt | sed  s:"`pwd`"/:: | sed "s/^[-dltrwx]*\ *[0-9]*\ [a-z]*\ *[a-z]*\ *[0-9]*//"'

[robg adds: This works only in csh; bash experts are welcomed to weigh in with their 'how to make this work in bash' feedback. I tried, but failed. I tried using backslashes to break up the alias into a displayable five-line cut-n-paste alias, but that also failed (I think xargs kills it, somehow). Finally, if you just want to test the alias at the command line, not in .cshrc, you'll have to remove the double quotes around both instances of pwd.]

Comments (9)


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