9
Dec/08
5

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 (4) 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