Tag: sort

Linux : Sort a list of IP address

like we saw previously in that article , it’s possible to ping an entire /24 subnet with a little convenient command.

64 bytes from 192.168.1.21: icmp_seq=1 ttl=64 time=0.163 ms
64 bytes from 192.168.1.31: icmp_seq=1 ttl=64 time=0.360 ms
64 bytes from 192.168.1.8: icmp_seq=1 ttl=128 time=66.8 ms
64 bytes from 192.168.1.32: icmp_seq=1 ttl=64 time=25.1 ms
64 bytes from 192.168.1.42: icmp_seq=1 ttl=255 time=1.93 ms
64 bytes from 192.168.1.46: icmp_seq=1 ttl=255 time=60.8 ms
64 bytes from 192.168.1.41: icmp_seq=1 ttl=255 time=67.0 ms
64 bytes from 192.168.1.254: icmp_seq=1 ttl=64 time=0.344 ms

 

The Problem is , the IP adresse are going to be displayed in the order they answer the ping , and some devices are going to answer faster than other , making a list that is not in order

the sort command in her default setting will sort using the first changing character , which is going to give me a list like that : 21, 254, 31, 32, 41, 42, 46, 8

If you have installed on you host a recent version of the sort command , you will be able to use sort -V
but on older and some embedded devices the -V option is not available ,

You can then launch the sort command with these options :

sort -n -t . -k 4,4

the result will be :

64 bytes from 192.168.1.8: icmp_seq=1 ttl=128 time=0.978 ms
64 bytes from 192.168.1.21: icmp_seq=1 ttl=64 time=0.246 ms
64 bytes from 192.168.1.31: icmp_seq=1 ttl=64 time=0.383 ms
64 bytes from 192.168.1.41: icmp_seq=1 ttl=255 time=76.5 ms
64 bytes from 192.168.1.42: icmp_seq=1 ttl=255 time=2.47 ms
64 bytes from 192.168.1.46: icmp_seq=1 ttl=255 time=65.4 ms
64 bytes from 192.168.1.254: icmp_seq=1 ttl=64 time=0.290 ms

 

if you need to sort a /16 list of ip address :

you can just add -k 3,3 to the command : sort -n -t .-k 3,3 -k 4,4