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; echo; echo | sort -n

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; echo; echo | ipsort

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!


  3. Alex says:

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

Leave a Reply