Susam Pal has an excellent post on sorting text in Emacs. Most experienced Emacers have probably seen most of the methods he talks about but unless you use them all the time, it’s easy to forget them. This post is a nice reminder and a useful summary that’s worth saving for future reference.
He starts with the simplest case of merely doing an alphabetical sort of the lines in a region with the sort-lines
command. Specifying the universal argument does a reverse sort. This single covers a lot of the cases you actually run across but, of course, there’s more.
If your data is vaguely table-like, you may want to sort the lines based on a particular column. The sort-fields
command handles this case for alphabetical columns and the related sort-numeric-fields
take care of the case where the data in the column is numeric. That makes sure that 20
sorts before 100
. In all these cases, it’s probably easier to call reverse-region
after a normal sort if you want a reverse sort.
Next, he considers sorting on multiple adjacent columns with sort-columns
. In this case, it make sense to specify the universal argument if you want a reverse sort. From there he moves on to the slightly more general case of using a regular expression to specify the sort key with sort-regexp-fields
. There are snares for the unwary with this command so be sure to read his two examples carefully.
Finally, he shows how to export the region to an external sort routine. If you’re familiar with the Unix sort
command this can sometimes be easier than trying to remember the specific Emacs commands.
As I say, this is a really nice post and well worth your attention.