prke1w
Last Updated: February 25, 2016
·
3.618K
· jeffremer
372909bbd2c8ec9f54a401c368789335

Sort Lines of Text in Any OSX Application

The Terminal is your Friend

Here's a simple workflow to quickly sort lines of text:

  1. Select text
  2. ⌘C
  3. Open Terminal
  4. sort | pbcopy
  5. ⌘V
  6. ⌘D

These steps will copy the selected text to the clipboard, run it through the sort command, then copy it back to your clipboard.

Many text-editors have built-in commands to sort lines of text, however Xcode doesn't. Something I regularly do is sort header #import statements, property names, @class forward-declarations, etc…so not being able to quickly sort lines is kind of irritating.

The above technique is pretty quick, but it could be quicker, especially if we could make it a single action.

Automate all the Things!

This is where Automator comes in. Automator lets you define services that are available to other applications from the Services menu in the menu bar and context menu.

Here's how you add a Sort Lines service (originally from epatel on Stack Overflow).

  1. Launch Automator.
  2. File > New, choose Service.
  3. Check the Output replaces selected text option.
  4. Add a Run Shell Script action.
  5. Set the shell script body to sort -f. You can use sort -f | uniq to get rid of duplicate lines which is useful for things like #import statements.
  6. ⌘S to save the Service and name it something like "Sort Lines."

After saving the Sort Lines service it becomes available via the Services menu whenever you have text selected, or by right-clicking any piece of selected text.

Keyboard Power

Creating a Service menu item is one step closer to adding custom text manipulations that aren't available by default in applications like Xcode. The final step is to assign it to a keyboard shortcut.

The OSX System Preferences > Keyboard > Keyboard Shortcuts preferences pane lets you assign keyboard shortcuts to menu items. Under the Application Shortcuts just add a new shortcut to any or all applications and name it precisely after the service you created ("Sort Lines").

Now you can sort lines of text in any OSX application just by selecting the text and hitting your keyboard shortcut.

Say Thanks
Respond