TextExpander: Sort Lines

A newer JavaScript based version of this snippet is now available and will run on TextExpander 5+ on the Mac and TextExpander 3+ on iOS.

TextExpander is a great piece of software that can save you a lot of effort when you want to insert pieces of boiler plate text. However it is a much more versatile piece of software and I’m particularly fond of its capability to process text using shell scripts. In this post I’m going to give some details about how I use it to sort lines of text into alphabetical order.

Whilst I’m sure many readers will have text editors that do this sort of sorting (I certainly do), I found myself occasionally wanting to sort text in other applications (e.g. Evernote, SideWriter) and it seemed cumbersome to open up a text editor just to do the sorting. This is where my TextExpander snippet came in.

I’ve used a Perl script to take lines of text on the clipboard and sort them alphabetically. The sort is case insensitive, but with a few small amendments you could make versions that are case sensitive or even to reverse the sort order.

The text in the clipboard is read into an array with each line being a new element. The array is then sorted and converted back into a string with a new line between each element.

e.g.

    red
    orange
    Yellow
    Green
    blue
    indigo
    violet

… in the clipboard would be output as …

    blue
    Green
    indigo
    orange
    red
    violet
    Yellow

The details for the snippet to do the sorting are shown below.

Label Sort text lines alphabetically
Description Sort text lines alphabetically (case insensitive) and output on separate lines.
Abbreviation sortalpha
Content
#!/usr/bin/perl -w

#Initialise.
use strict;
my $text =`pbpaste`;

#Convert every line into a new element of an array.
my @arrText = split "\n", $text;

#Sort the array (case insensitive).
@arrText = sort  { "\L$a" cmp "\L$b" } @arrText;

#Output the sorted array as an entry on each line.
print join("\n", @arrText);

This snippet can be downloaded as part of the Thought Asylum Clipboard snippet group.

Author: Stephen Millard
Tags: | perl | textexpander |

Buy me a coffeeBuy me a coffee



Related posts that you may also like to read