Linux Bash – How to Select and Sort IP Address Keeping the Whole Line

bashlinuxsort

So I need to sort the IP Addresses and then sort my line by them.

I can sort IP addres in a file by using : sort -n -t . -k1,1 -k2,2 -k 3,3 -k4,4

If my file looks like :

    add method1 a.b.c.d other thing
    add method2 e.f.g.h other thing2
    add method2 a.b.c.d other thing2
    add method5 j.k.l.m other thing5
    add method3 a.b.c.d other thing3
    add method1 e.f.g.h other thing2

But in this case, field 1 will be :

    add method1 a
    add method2 e
    add method2 a
    add method5 j
    add method3 a
    add method1 e

And field 4 will be :

    d other thing
    h other thing2
    d other thing2
    m other thing5
    d other thing3
    h other thing2

How and What tools should I use to sort my IP addresses and then sort my lines by them.
Thanks in advance.

EDIT : Example modfied. There is several line with the same IP address but with different text and in a random order.

Best Answer

This script copies the ip address from field 3 using awk to the start of the line with a "%" separator, then does the sort on the ip address now in the first field, then removes the added part.

awk '{print $3 " % " $0}' |
sort -t. -n -k1,1 -k2,2 -k3,3 -k4,4 |
sed 's/[^%]*% //'

If the field with the ip address is not a constant, you can auto-detect it on each line. Replace the awk above with:

awk '{ for(i=1;i<=NF;i++)
         if($i~/^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$/)break;
       print $i " % " $0
     }' |
Related Question