Sorting a list of IP addresses
Suppose we have a list of IP addresses that we want sorted.
[prune:~] malte% cat iplist 1.2.3.4 1.121.3.222 1.21.3.4 1.121.3.5 1.121.3.4
Using sort we can specify that numeric comparison should take place and we end up with the following, sorted list.
[prune:~] malte% sort -n iplist 1.121.3.222 1.121.3.4 1.121.3.5 1.2.3.4 1.21.3.4
This isn't good enough as the numeric comparison is done only on the initial digit and the rest of the sort is performed lexically. For example 1.121.3.222 should come after both 1.121.3.4 and 1.121.3.5. The solution is to specify what fields to sort each line on. Using the -t switch we tell sort that fields are separated by dots. We then specify what fields to sort on using combined +n -m switches, where n and m are field indicies.
[prune:~] malte% sort -n -t '.' +0 -1 +1 -2 +2 -3 +3 -4 iplist 1.2.3.4 1.21.3.4 1.121.3.4 1.121.3.5 1.121.3.222
Voilą! A sorted list of IP addresses.
