Sort lines in a region

Select a region of text and then use M-x sort-lines to sort the lines into alphabetical order (really ascii-betical order). To reverse the sort, we give the command a prefix argument by using C-u M-x sort-lines. The keybinding C-u provides a prefix argument to the command that follows. In the case of sort-lines, the documentation (C-h f sort-lines) tells us that giving an argument will reverse the sort, hence using C-u.

To sort numerically, use M-x sort-numeric-fields. This sorts the lines into ascending numerical order. For simple tabular data, this command can sort by a particular field, if each line contains the same number of fields separated by whitespace. To do this we need to provide a numeric argument, which we do with e.g. C-u 3 M-x sort-numeric-fields to sort by the 3rd field on each line.

To reverse the numeric sort, simply perform the normal sort, and then select the region again and reverse the order of the lines with M-x reverse-region.

As a final tip, after you run the sort command, you will find that the region you originally selected is no longer highlighted, but you need it to be to run reverse-region. Don’t touch the mouse, just hit C-x C-x (which runs the command exchange-point-and-mark) which exchanges the point (the cursor) and the mark (the beginning of the region you previously selected) and activates (highlights) the region between them. The net effect is that the region you previously selected is now selected again.

Update

As pointed out below by commenter Noam Postavsky, you do not need to use C-x C-x to reactivate the region before using reverse-region. This is because the region still exists even though it is not highlighted, so the reverse-region command works just fine. I’ve written a short post about emacs regions to clarify this behaviour for myself.

  • Noam Postavsky

    > you will find that the region you originally selected is no longer highlighted, but you need it to be to run reverse-region.

    You *don’t* need to activate (highlight) the region to run reverse-region

    • Ben Maughan

      Thanks for the correction! See above for an update.

  • Boris Kheyfets

    The variable `sort-fold-case’ determines whether alphabetic case affects the sort order.