Sorting a string of IP addresses


I had a samba box in which access was limited to a list of IP addresses. This appears as a single long string of addresses separated by commas in the smb.conf file as well as SWAT's representation of that file. The addresses had been added randomly, so after a while it was difficult to see which addresses were already in there and which weren't. So, I decided to sort the addresses. I copied the string of addresses from the smb.conf file, assigned it the variable n and then did this:

echo $n|tr ',' '\n'|sort -n -t . -k 1,1 -k 2,2 -k 3,3 -k 4,4|sed ':a;N;$!ba;s/\n//g'

Taking it apart, it replaces the commas with newlines, sorts the addresses numerically, and then uses sed to put the lines back into a single, comma-delimited string. Info about the sort command can be found on Paul Heinlein's page, and info on getting sed to replace newlines with commas can be found in secion 5.10 of Eric Pement's sed FAQ.

08/06/2004