February 2, 2016

Unix/Linux: Sort command to sort IP Address

Sometime while dealing with list of  IP Address, we might need to sort IP Address in order. "sort" command can be use for sorting such list. But one must know how to properly use sort command to sort IP Addresses because of its dotted-quad notations.

While using sort command without options, it sorts list of IP Address based upon alphabetic order.

Though using sort -n  will sort list of IP Address in numerical order but still it has limitation because of dotted-quad notation of IP Address. Therefore the correct way to sort IP Address is to order the list numerically by considering IP Address as set of four fields having numeric value separated by dot.

Lets take a example:

$ cat ip.txt
9.1.4.4
9.1.4.4
9.1.78.4
149.4.78.4
149.4.78.41
14.4.78.41
10.4.7.41



$ sort -n -t . -k 1,1 -k 2,2 -k 3,3 -k 4,4 ip.txt
9.1.4.4
9.1.4.4
9.1.78.4
10.4.7.41
14.4.78.41
149.4.78.4
149.4.78.41


where,
  • -t : Set field to . (dot)
  • -n : sort list numerically
  • -k options:  Sort via a key using start and stop position




3 comments:

  1. Firstly, Thanks for all the useful insights. I would like to thank you for putting emphasis on how relevancy playing a big role in hosting industry. I appreciate your hard work. Keep posting new updates with us.

    Offshore dedicated server

    ReplyDelete
  2. Thank you so much as you have been willing to share information with us. We will forever admire all you have done here because you have made my work as easy as ABC. https://192-168-i-i.com/

    ReplyDelete