Last Updated: November 02, 2023
·
12.78K
· jeffremer

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.

4 Responses
Add your response

Awesome. Thank you for writing this up!

over 1 year ago ·

pbpaste | sort | pbcopy
is what ended up working for me

over 1 year ago ·

None of this works. To be fair, Apple screws up every macOS update, and a lot of automator doesn't work.
The terminal method doesn't either.
I'm kind of surprised it's not a built-in Services option.
Automator can't get past step 1, because there's no "service" in the new types.
SO, I'm still looking... It would be a nice right-click service to have.

over 1 year ago ·

I found it. It's in the new app "Shortcuts".
Apple says they're trying to replace Automator, but there's a lot that's broken, and Shortcuts can't do it.
Like terminal commands.

over 1 year ago ·