9
Dec/08
9

Quickie: Sort IP-Addresses on linux command line (bash)

I have some ip-addresses in a text file. One address per line. The addresses are unsorted. I’d like to have them in a correct order. Some example from file “addresses”:

192.168.1.1
192.168.1.4
80.68.11.31
192.168.10.33
192.168.11.3
81.67.12.31

Now I run sort with the following options to sort these ip addresses:

:> sort -t . -k 1,1n -k 2,2n -k 3,3n -k 4,4n addresses

The sort command sends this to stdout:

80.68.11.31
81.67.12.31
192.168.1.1
192.168.1.4
192.168.10.33
192.168.11.3

Short explanation for the params:

-t .: Use dot as field seperator. -k 1,1n: First sort key is field 1, sort it numeric.

The lines are sorted by each sort key one after another.

Filed under: Open Source
Comments (8) Trackbacks (1)
  1. enderwigNo Gravatar
    16:50 on October 6th, 2010

    thank’s for the info!

  2. Joe KlemmerNo Gravatar
    17:09 on October 6th, 2010

    Man! I need to pay more attention to man pages. I could have used the -t so many times in the past. Although, it was fun hacking up an awk command line to do this.

  3. fantaNo Gravatar
    12:17 on October 7th, 2010

    Good job :) . Thx.

  4. nomanNo Gravatar
    14:47 on October 20th, 2011

    thanks for the example, it is useful

  5. jorgeNo Gravatar
    22:06 on February 13th, 2012

    excellent, thanks!

  6. TroyskiNo Gravatar
    09:49 on February 24th, 2012

    Very useful. :-)

  7. ronNo Gravatar
    21:17 on April 22nd, 2012

    Doesn’t work on all IP ranges. Problem is with the following: 192.168.2.100 19.216.82.100 1.92.168.210

    The IP’s like in the example work fine, but these trip up the sort. I don’t know how to sort the example I gave. You gave me places to start looking though, so thank you very much.

  8. ronNo Gravatar
    01:43 on April 29th, 2012

    Oops. It does work as you describe. I had characters in front of the IP addresses, so it failed. Removed the characters in VI, sorted as you describe, then put the characters back in and all was well. Thanks again.