0

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

1
  • You posted sample input but you forgot to add the expected output given that input and the command you provided. Commented Dec 3, 2017 at 21:19

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you !!! It's exactly what I needed. I didn't know that we can tidy up ARGVs. :)
Well... you kinda/sorta can but not really. What I mean is you can delete it or set it to null and then the body of the script will skip it, but if you looped through ARGV in the END section there'd still be a null string entry there. You know you can just leave out the whole END section right? I'm not sure if you're printing something in it because you thought you had to have it or what. Ditto for BEGIN of course but you're actually using that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.