Today’s sysadmin tip: ipsort – sort text by ip address

Quite often, I have a list of ip addresses or networks available as an output from a list or a script, and would like to sort them based on the address. The usual unix sort -n does numerical sort, so the list often becomes almost correct

$ (echo 192.168.1.1; echo 192.168.10.2; echo 192.168.2.10) | sort -n 
192.168.10.2
192.168.1.1
192.168.2.10

But grep has a few tricks up its sleeves. Numerical sort by field:

$ alias ipsort="sort -n -t . -k 1,1 -k 2,2 -k 3,3 -k 4,4"

$ (echo 192.168.1.1; echo 192.168.10.2; echo 192.168.2.10) | ipsort
192.168.1.1
192.168.2.10
192.168.10.2

Nice, isn’t it?

3 Responses to “Today’s sysadmin tip: ipsort – sort text by ip address”

  1. Damien says:

    Nice tip :) I add it to my .zshrc.
    Thank you !

  2. Dave says:

    sort -V
    sort –version-sort

    This’ll sort both IPv4 and IPv6 addresses correctly, even a mixed list containing both types!

    Cheers!

  3. Alex says:

    Else, #gsort -V works well for this use case.

Leave a Reply