Sorting IP Addresses

Ever noticed how the Unix sort command can’t make anything of IP addresses when you use just a numeric sort, like this:

hessch@galileo:~$ sort -n ip.txt
1.2.3.4
5.6.7.8
10.200.219.5
10.20.30.40
10.3.5.6
89.2.177.21
193.18.4.1

As you notice, for instance 10.20.30.40 is listed below 10.200.219.5, which is wrong, of course. The trick is to define every octect in the dotted quad notation as a key for sort like this:

hessch@galileo:~$ sort -t. -n -k1,1 -k2,2 -k3,3 -k4,4 ip.txt
1.2.3.4
5.6.7.8
10.3.5.6
10.20.30.40
10.200.219.5
89.2.177.21
193.18.4.1

There you have it, using sort -t. -n -k1,1 -k2,2 -k3,3 -k4,4 all addresses are sorted properly.

Comments