Xah Lee has caught the VimGolf with Emacs bug and proposed an interesting challenge. The final part of the solution involved sorting the following list by the number of square kilometers.
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²
Normally this wouldn’t be much of a problem but two things make it more difficult than usual. First, the line for Korea has an extra field so commands like sort-fields
or sort-numeric-fields
don’t work. Second, the numbers have commas in them so the numeric sorts don’t work.
I remarked on Xah’s blog that I had tried sort-regexp-fields
but that that didn’t work because the sort was lexicographic rather than numeric. Then jm commented that the lexicographic sort will work if you include the spaces in front of the shorter numbers. He proposed using sort-regexp-fields
with the regular expression .*\([0-9 ,]\{9\}\) km
. That did the trick and I thought it was probably as simple a solution as we were apt to find.
Later I suddenly realized that an even simpler solution based on the same idea was to use sort-columns
. To use that function, you mark the rectangle containing the columns you want to sort on and then just call sort-columns
. Thus, I placed the point two spaces before 423,970 on the first line, typed 【Ctrl+Space】 to set the mark, moved the point to right after 1,964,375 on the last line, and typed 【Meta+x】 sort-columns
to sort the list. That worked perfectly and is a reasonably concise solution.
As usual, Emacs had the right tool to get the job done even if it took a little effort to find it. Maybe next time this solution will jump right into my head. Or not.