I’m on a bit of a productivity kick lately. I’m trying to listen to the little voice in my head that speaks up when I’m doing something incredibly tedious and error-prone, and could clearly be automated.
Some people would say that spending 3 hours cranking out a script that might save you at most a minute or two each time you use it is the opposite of productivity, but I beg to differ. Yes, it may take a while to fully earn back the time I spend on such modest life improvements, but the little changes often clear the way for bigger changes down the road.
How many of you have ever stared at a folder in the Finder, teeming with files of varying types and names, and wished you could easily select by regular expression? Well, your reward for reading this blog is that as of today, you can!
I was inspired by a project of mine whose directory hierarchy was “out of control.” Since the project started out small, I had colocated all of the source files, images, documentation, reference materials, etc., in one directory. Now I’m looking at it and thinking, “gosh, I’d like to at least put all the source files in a sub-folder, but it’s drag to select every ‘.m’ and ‘.h’ file by hand.”
At first I tried to accomplish the task in AppleScript alone. Among the many things missing from AppleScript is a built-in regular expression engine, so I knew I’d have to either install a scripting component, or resort to Mac OS X’s built-in command line tools. My script started out as an AppleScript that merely called out to perl (via “do shell script”) to handle the regular expression parsing:
This worked great, but as expected, those repeated “do shell script” calls dogged performance big time. The point of this is to automate a task so that it happens in the blink of an eye. If I have to wait for a long pause, then I’ve just replaced one frustration with another!
How to avoid the delay of the repeated “do shell script” commands? I thought about spitting out the names of the files to a temporary file, and running perl just once against that file. Yeah – complicated and I don’t like to use temporary files when it’s possible to avoid them.
I decided it was time to approach the problem from the other angle. There’s no reason I can’t write the script in Perl and just call out to AppleScript as necessary to interface with the Finder. An added benefit is that I can easily use the Perl script from the command line or a script menu. I set the script up as a FastScripts Finder-specific script, and applied the keystroke “Cmd-Opt-S” as a shortcut. Now when I’m looking at a window like this:
I just hit Cmd-Opt-S to bring up this dialog, enter a regular expression:
And end up with this!
Can’t wait to get your hands on this? Feel free to download a copy of “Select Regular Expression” from the Red Sweater scripts page. Enjoy!
Update: Version 1.0.1 of the script saves and restores the regular expression you enter, so the dialog is always pre-populated with the last string you tried.