Emacs: Sort Lines

By Xah Lee. Date: . Last updated: .

Sort Lines and Reverse Lines

Alt+x sort-lines

Sort lines in text selection.

Alt+x reverse-region

Reverse lines order in text selection.

Sort by Number Column

Alt+x sort-numeric-fields

Sort lines by a specific column, as number.

Fields are separated by space or tabs. First field is indexed as 1.

For example, to sort

aa 77
cc 333
bb 9

to

bb 9
aa 77
cc 333

Type Ctrl+u, then 2, then Alt+x sort-numeric-fields.

Sort by Text Column, as String

Alt+x sort-fields

Sort lines by a specific column, as string.

Fields are separated by space or tabs. First field is indexed as 1.

Call Emacs: Universal Argument (C-u prefix arg) to give argument.

Sort by Rectangle Selection

Alt+x sort-columns

Sort lines by a rectangle selection, as string.

The column is specified by the position of mark and cursor.

So, place the cursor at the upper right, mark it, then move to lower left of our number, like this:

California             423,970▮km²
Taiwan                  36,008 km²
Japan                  377,944 km²
Germany                357,021 km²
Iraq                   438,317 km²
Iran                 1,648,195 km²
Korea (North+South)    219,140 km²
Mexico             ▮1,964,375 km²

Then Alt+x sort-columns

result:

Taiwan                  36,008 km²
Korea (North+South)    219,140 km²
Japan                  377,944 km²
Germany                357,021 km²
California             423,970 km²
Iraq                   438,317 km²
Iran                 1,648,195 km²
Mexico               1,964,375 km²

Emacs, Work on Lines