titi157
titi157

Reputation: 157

AWK Script File : Combine 2 Commands

I would like to combine these 2 commands :

COMMAND 1:

`BEGIN {
    ip = ARGV[2]
    split(ip, octets, ".")
    for (i = 1; i <= 4; i++) {
        dec += octets[i] * 256 ** (4 - i)
    }
    printf("%i\n", dec)
}`

COMMAND 2:

`BEGIN{
    FS=",";
}
{
    if ($4 == dec){
        print $7;
    }
}
END {
    print "END";
}`

FILE TO READ:

"16777216","16777471","apnic","1313020800","AU","AUS","Australia"
"16777472","16777727","apnic","1302739200","CN","CHN","China"
"16777728","16778239","apnic","1302739200","CN","CHN","China"
"16778240","16779263","apnic","1302566400","AU","AUS","Australia"
"16779264","16781311","apnic","1302566400","CN","CHN","China"

The first command is used to convert an IPV4 address into decimal and the second one is used to search the decimal in a .csv file.

Therefore, I would like to use a command like the following one: awk -f script.awk fileToRead.csv 10101100.00010000.11111110.00000001

Upvotes: 0

Views: 51

Answers (1)

Ed Morton
Ed Morton

Reputation: 203254

Concatenating your 2 files would just about do what you want (after zapping ARGV[2] so it's not treated as a file):

BEGIN {
    ip = ARGV[2]
    split(ip, octets, ".")
    for (i = 1; i <= 4; i++) {
        dec += octets[i] * 256 ** (4 - i)
    }
    ARGV[2] = ""
    ARGC--
}

BEGIN{
    FS=",";
}
{
    if ($4 == dec){
        print $7;
    }
}
END {
    print "END";
}

but I'd recommend you rewrite it as:

BEGIN {
    split(ip, octets, /[.]/)
    for (i = 1; i <= 4; i++) {
        dec += octets[i] * 256 ** (4 - i)
    }
    FS=","
}
$4 == dec {
    print $7
}
END {
    print "END"
}

and then call it as:

awk -v 10101100.00010000.11111110.00000001 -f script.awk fileToRead.csv 

just to tidy it up a bit.

Upvotes: 1

Related Questions