AWK脚本文件:组合2个命令

时间:2017-12-03 21:09:25

标签: bash csv awk

我想结合这两个命令:

命令1:

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

命令2:

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

阅读文件:

"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"

第一个命令用于将IPV4地址转换为十进制,第二个命令用于搜索.csv文件中的十进制数。

因此,我想使用如下命令: awk -f script.awk fileToRead.csv 10101100.00010000.11111110.00000001

1 个答案:

答案 0 :(得分:1)

连接你的2个文件只会做你想要的(在切换ARGV [2]之后它不被视为文件):

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";
}

但我建议你把它重写为:

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

然后将其命名为:

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

只是为了整理一下。