Sorting Strings in a Line in Emacs
25 Apr 2025 Charles Choi
If you ever find yourself wanting to sort strings in the same line in Emacs, sort-regexp-fields
is your friend.
For example if you had the text:
["dog", "cat", "apple", "baseball"]
You can mark (select) that line as a region and invoke sort-regexp-fields
. When called interactively, this command will ask twice in the mini-buffer for two regexps. The first regexp describes the record (or string pattern) that matches the region of text you want considered for sorting. Note this regexp is not used to actually sort the text.
For the example above, we’ll use a record regexp using the character class [:graph:]
to specify the content within double quotes. We’ll also group that content using \(
… \)
.
Regexp specifying records to sort: "\([[:graph:]]*\)"
The second prompt will ask for a key regexp that sort-regexp-fields
will use to actually sort the text. Since we used a grouping construct in the first regexp, we can use a number reference.
Regexp specifying key within record: \1
The end result is:
["apple", "baseball", "cat", "dog"]
Using [:graph:]
presumes there are no spaces in the content between the double quotes. Let’s try a different example with record regexp that is less filtering. We will keep the key regexp at \1
.
["hi there", "good to go", "a bottle", "can't go there"]
Regexp specifying records to sort: "\([^"]*\)"
The result is:
["a bottle", "can't go there", "good to go", "hi there"]
Closing Thoughts
sort-regexp-fields
is a really great tool to have in your back pocket. That said, knowing what kind of regexp to use is a bit more challenging to remember. For motivated readers, I'd offer that knowing how character classes work is worth the time invested as other GNU tools like grep also support them. I wrote this post for future-me, but perhaps you might find this tip useful too.