Filter text with shell commands

Today's Best Tech Deals

Picked by Macworld's Editors

Top Deals On Great Products

Picked by Techconnect's Editors

The bash shell has a bunch of commands for processing text—things like sort (which can sort lines in a text file), tr (which you can use to convert uppercase to lowercase, or to delete entire classes of characters), and so on. If you’d like to access those tools from within the OS X GUI, reader michaeltyson came up with an Automator service—which you can build yourself or download—that will let you do so.

To create the service yourself, open Automator and select Service from the template window. Drag Run Shell Script from the Utilities actions into the workflow workspace. Copy the script below, then paste it into the script window:

result=`osascript -e 'tell application "System Events"' -e 'activate' -e 'set result to (display dialog "Enter shell command to filter selected text through:" with title "Filter text" default answer "sort" buttons {"Cancel", "Filter"} default button 2)' -e 'text returned of result & "%%SEP%%" & button returned of result' -e 'end tell' | sed 's/"/\"/g'`

[ ! "$result" ] && cat && exit;
button=`echo "$result" | sed s/.*%%SEP%%//`
command=`echo "$result" | sed s/%%SEP%%.*//`

[ "$button" = 'Cancel' ] && cat && exit;

cat | sh -c "$command"

Save that (giving it whatever name you like) to /Library/Services (authenticating if necessary).

If you’d rather not do all that yourself, you can download the workflow; after you unzip it, save it to to the same folder.

That done, you can select some text in any app, right-click, and select your workflow from the Services submenu. That’ll pop up a Filter Text dialog. Enter the shell command you want to use there, then click on Filter. The workflow will run your shell command and replace the selected text with the result. michaeltyson suggests a couple of sample commands; you can find more here or by poking around in the bash man pages.

Note: When you purchase something after clicking links in our articles, we may earn a small commission. Read our affiliate link policy for more details.
Shop Tech Products at Amazon