Using GNU Sort for IP Addresses
This document shows how to use the GNU sort utility to properly sort IP addresses in true number order.
The short answer. Here's the invocation that works. It's explained in the long answer that follows.
sort -n -t . -k 1,1 -k 2,2 -k 3,3 -k 4,4
The long answer. More than once I've been confronted with a list of IP addresses that I've wanted to sort into numeric order. Trouble is, the dotted-quad notation isn't sort-friendly. Consider the following raw list of addresses.
cat addresses.txt126.96.36.199 188.8.131.52 184.108.40.206 220.127.116.11 18.104.22.168 22.214.171.124
Without options, sort will rely on alphabetic order, which certainly won't do what you want:
sort addresses.txt126.96.36.199 188.8.131.52 184.108.40.206 220.127.116.11 18.104.22.168 22.214.171.124
There are so many mistakes in this ordering I'm not even going to try to list them all.
The situation is only marginally improved when using the
sort -n addresses.txt126.96.36.199 188.8.131.52 184.108.40.206 220.127.116.11 18.104.22.168 22.214.171.124
The first set of numbers in each dotted-quad sort correctly—5 preceeds 19, and 129 is at the tail end—but the internal
numbering still gets improper treatment.
126.96.36.199 is listed prior to
188.8.131.52 because 220 is alphabetically prior to 24. Likewise the two
19.20.x.x addresses are mixed up because 203 is alphabetically prior to 21.
The solution is to tell sort to order the list numerically, considering each address as a set of four numeric fields, each separated by a dot. Below I am using nbtstat to scan my work network and using sort to sort the output appropriately.
nbtscan 184.108.40.206/16 | sort -n -t . -k 1,1 -k 2,2 -k 3,3 -k 4,4------------------------------------------------------------------------------ IP address NetBIOS Name Server User MAC address Doing NBT name scan for addresses from 220.127.116.11/16 18.104.22.168 INTZ-DHCP
INTZADM 00-d0-b7-58-dc-18 22.214.171.124 INTZ-DNS02 INTZ-DNS02 00-d0-b7-58-e0-ab 126.96.36.199 VMSERVER ADMINISTRATOR 00-00-b4-98-1a-e6 188.8.131.52 PLUTO 00-d0-b7-83-17-ca 184.108.40.206 KOIOS SHART 00-03-47-a5-1a-04 220.127.116.11 BARCODE-WKSTN RSCHAFFNER 00-b0-d0-76-fd-e2 18.104.22.168 INTRUSIO-M77QUC GHEMPHILL 00-01-03-82-db-e2 22.214.171.124 RIMDEMO 00-03-47-a5-92-0d 126.96.36.199 BBITTLE-LT 00-11-43-3b-6f-51
In English, you're saying, Yo, sort! I've got here a list of
-n), but each item in the list consists of some subnumbers, fields set apart from the
others by a dot (
-t .). Sort first by the first field, and only the first field (
-k 1,1), then by the second and only the second (
-k 2,2), and so on (
-k 3,3 -k 4,4).