≡ Menu

Linux / UNIX Shell: Sort IP Address

  • Raymond September 17, 2008, 3:01 pm

    I’ve been follow your site 6 months, faq section is always very informative. keep up your good work..

  • Brad October 16, 2009, 7:57 pm

    You allude to sorting all columns in an IP address, but don’t specifically state how to.
    Here’s the sort command to sort all IP addresses:
    sort -t . -k 1,1n -k 2,2n -k 3,3n -k 4,4n /path/to/file

    Also, since i’m here, i wanted then to reverse my IP addresses so i could build a reverse zone file for DNS. I found an easy way:
    IP=(${IP//./ })
    echo $Rev

    Thanks to you and your sort command for getting me started.

  • Vivek Umasuthan November 24, 2009, 9:14 pm

    This was really useful. Thanks for the help.

  • Kacak April 14, 2011, 6:54 am

    Thanks for the great sharing… I know this is for unix/linux machine, but i would appreciate if you could share something similar (to sort ip addresses) on windows OS as well.


  • tc June 14, 2011, 12:52 pm

    I have a text file of IP addresses that I’d like to sort, which might look something like this: 50 100 50 80
    ab32::ff0:c23a 123 ff::ab12 80 80 123

    I’d like to sort on the first column of IP addresses, then the third column of IP addresses. It doesn’t matter if IPv4 comes before IPv6 or vice versa.

    This sort method seems to work only for a text file containing a single column of IPv4 addresses. It’s a tough problem. This is a start for me, and I’ll have to do some trial and error and reading of “man sort.” Any tips would be appreciated.


  • joe January 15, 2015, 10:17 am

    You can also use the -V, –version-sort option :
    natural sort of (version) numbers within text

  • James February 23, 2015, 7:55 pm

    Is it possible to sort by a column and then within that column? Say I had a file with a bunch of text similiar to:

    hostname1 has address
    hostname2 has address
    hostname3 has address
    hostname4 has address
    hostname5 has address

    …and so on. And I wanted to sort the file by the 4th column and then within *that* column sort the IPs numerically so that would show up above .. ect keeping the rest of the line intact.


  • dtkerns September 25, 2015, 3:32 pm

    @ James

    awk '{print $4 ":" $0}' file | sort -t. -n -k1,1 -k2,2 -k3,3 -k4,4 | cut -t: -f2-
  • Jim March 9, 2016, 7:38 pm

    Much obliged, I’ve been looking for this explanation for years.

  • Ray June 1, 2016, 7:21 pm

    Love it! Great examples and very helpful

  • Security: Are you a robot or human?

    Leave a Comment

    You can use these HTML tags and attributes: <strong> <em> <pre> <code> <a href="" title="">