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.
Without options, sort will rely on alphabetic order, which certainly won't do what you want:
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
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.
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.
In English, you're saying, Yo, sort! I've got here a list of
This page was created in 0.00086 seconds
Comments and Questions
Last modified: May 28 2007.