how to sort ipv4 addresses with unix sort

this will sort a list of ipv4 addresses:

  • sort -g -t . -k 1,1n -k 2,2n -k 3,3n -k 4,4n

the -g option in addition to all the n’s in the field definitions may seem like overkill, but i found it necessary on more than one occasion. this is sort of a paranoid command line 'cos i sometimes work with lists of addresses that number in the thousands, so i don’t want to have to validate the output manually; this has never failed to give the correct output.

example

sort -g -t . -k 1,1n -k 2,2n -k 3,3n -k 4,4n <<EOM
11.27.255.178
11.27.255.185
11.27.3.55
11.47.36.136
11.127.38.12
11.27.38.144
11.27.42.169
11.27.54.192
11.27.5.45
11.27.61.112
11.37.61.112
11.27.141.20
EOM
11.27.3.55
11.27.5.45
11.27.38.144
11.27.42.169
11.27.54.192
11.27.61.112
11.27.141.20
11.27.255.178
11.27.255.185
11.37.61.112
11.47.36.136
11.127.38.12