从外部文件接收字符串时,AWK将其转换为整数 - 不正确

时间:2014-08-14 15:51:10

标签: awk cygwin gawk

我有一个奇怪的AWK行为:AWK脚本中的字符串被转换为整数没有问题,但是相同的字符串 - 当从外部接收时,不能正确转换为整数。

例如,当从脚本中收到字符串total_bytes时:

$ cat sample.awk 
END {
    total_bytes = "113402391" ;
    #total_bytes = $8
    total_bits = (total_bytes) * 8 ;
    print "Total transmitted bytes:", total_bytes ;
    print "Total transmitted bits:", total_bits ;
}
$ cat ./one_liner | awk -F, -f sample.awk 
Total transmitted bytes: 113402391
Total transmitted bits: 907219128
$

正确计算total_bits变量


然而,如果我尝试使用来自外部 AWK脚本的输入来做同样的事情:

$ cat sample.awk 
END {
    #total_bytes = "113402391" ;
    total_bytes = $8
    total_bits = (total_bytes) * 8 ;
    print "Total transmitted bytes:", total_bytes ;
    print "Total transmitted bits:", total_bits ;
}
$ cat one_liner 
"117403","885.406632000","192.168.0.25","192.168.0.26","TCP","60","8080 > 61165 [ACK] Seq=107051610 Ack=134 Win=262144 Len=0","113402391","2014-08-06 12:50:50.564785000"
$ cat ./one_liner | awk -F, -f sample.awk 
Total transmitted bytes: "113402391"
Total transmitted bits: 0
$ 

total_bits变量计算错误 - 0


环境:
操作系统:CYGWIN_NT-6.1-WOW64 1.7.29(0.272 / 5/3)i686 Cygwin
AWK:GNU Awk 4.1.1,API:1.1(GNU MPFR 3.1.2,GNU MP 6.0.0)

1 个答案:

答案 0 :(得分:3)

原因是,$8"xxxx"并带引号!

所以awk做的是8* "12334",它会是0

kent$  awk 'BEGIN{print (8 * "\"10\"")}'
0

快速解决方案是从"移除$8,然后再进行计算。