Sorting by IP Addresses

Recently, I needed to sort an Org mode table by a column having IP addresses. For example, given the table

|            IP | 11/01 | 11/02 | 11/03 |
|---------------+-------+-------+-------|
|    10.1.213.5 |     2 |     1 |     0 |
|  172.25.100.1 |     4 |     1 |     1 |
|   10.234.4.55 |     1 |     1 |     5 |
|  192.168.7.11 |     2 |     1 |     3 |
| 10.25.215.200 |     1 |     3 |     1 |
|    172.35.0.1 |     2 |     5 |     1 |

I want to sort on the IP column to get

|            IP | 11/01 | 11/02 | 11/03 |
|---------------+-------+-------+-------|
|    10.1.213.5 |     2 |     1 |     0 |
| 10.25.215.200 |     1 |     3 |     1 |
|   10.234.4.55 |     1 |     1 |     5 |
|  172.25.100.1 |     4 |     1 |     1 |
|    172.35.0.1 |     2 |     5 |     1 |
|  192.168.7.11 |     2 |     1 |     3 |

That turns out to be surprisingly difficult. There's no built-in method and I couldn't find an appropriate sort routine that exposed the comparison function so that I could write my own.

The normal Unix sort can sort IP addresses with

sort -n -t . -k 1,1 -k 2,2 -k 3,3 -k 4,4

Not easy or pretty but at least it gets the job done. My first attempt to get this to work was to mark the whole table except for the header line and the following rule line and then pipe it into sort with 【Ctrl+u Meta+|】. Sadly, this didn't work because of the | that begins each line.

Next, I tried marking the rectangle comprising the data of the table with 【Ctrl+x Space】 and then piping it into sort as before. That didn't work either.

Finally I remembered that I have cua-selection-mode enabled to mark rectangular regions. I marked the data with that and piped it into sort. Happily, that worked. If you haven't already enabled cua-selection-mode, you should. It's really useful.

I wouldn't think sorting IP addresses would be that unusual but there's no support for it all in Emacs. Most utilities do no better. Even sort only manages with some trickery. It's probably just that IP addresses weren't as ubiquitous as they are now when Emacs and those utilities were written. Or maybe I'm the only one who wants to sort by IP address.

So I solved the problem, sort of, but, really, it's a terrible solution. After a bit of thought, I ginned up a patch and sent it off to the Org mailing list. Tomorrow, I'll tell you the rest of the story.

This entry was posted in General and tagged . Bookmark the permalink.
  • cayetano santos

    Another option would be using org-babel, selecting first column of your table by its name as an input variable to one "src sh" block ...

    • jcs

      Nice idea. Especially if the table is in an Org file that's going to be exported for publishing. The code-block could do the sort at export time to make sure things are ready for publication.