Sort Lines of Text in Any OSX Application
The Terminal is your Friend
===================
Here's a simple workflow to quickly sort lines of text:
- Select text
- ⌘C
- Open Terminal
sort | pbcopy
- ⌘V
- ⌘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).
- Launch Automator.
- File > New, choose Service.
- Check the Output replaces selected text option.
- Add a Run Shell Script action.
- Set the shell script body to
sort -f
. You can usesort -f | uniq
to get rid of duplicate lines which is useful for things like#import
statements. - ⌘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.
Written by Jeff Remer
Related protips
4 Responses
Awesome. Thank you for writing this up!
pbpaste | sort | pbcopy
is what ended up working for me
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.
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.