我正在尝试使用awk读取包含字母数字字符的系统计数器文件中的数字总数整数(total=*****)数字,而不将结果管道传输到另一个命令。
即:
TCP time wait closed (net): 0 (total=0)
TCP gc closed (net): 0 (total=0)
TCP internal closed (net): 0 (total=0)
192.168.254.2:80 sockets (cpu0) (knet): 0 / 0 (total=0)
一开始我试着:
awk -F "total=" '{print $2 }'` counters
导致:
0)
0)
0)
0)
问题是")"字符,它将导致系统读取错误,因为它不是数字。然后我将第一个awk结果管道化为:
awk -F '[^0-9]+' '{OFS=" "; for(i=1; i<=NF; ++i) if ($i != "") print($i)}'
只读数字。结果是:
0
0
0
0
在bash中工作得很好。但是,我使用的系统不理解第一个awk参数中的管道,如果我配置了这个,它将导致以下错误:
awk -F "total=" '{print $2 }' counters | awk -F '[^0-9]+' '{OFS=" "; for(i=1; i<=NF; ++i) if ($i != "") print($i)}`'
awk: cmd. line:1: fatal: cannot open file `counters' for reading (No such file or directory)"
任何想法如何编写一个awk,可以提取的数字在(total=*)?
知道如何编写一个可以提取数字的awk吗(total=*) ?
如果你可以使用[GNU awk],下面的脚本:
awk '{$0=gensub(/.*total=(.*))/,"\1","1",$0);print}' file
应该做。
样本运行$ cat 38081612
TCP time wait closed (net): 0 (total=21)
TCP gc closed (net): 0 (total=28)
TCP internal closed (net): 0 (total=45)
192.168.254.2:80 sockets (cpu0) (knet): 0 / 0 (total=100)
$ awk '{print gensub(/.*total=(.*))/,"\1","1",$0)}' file
21
28
45
100
awk[用户指南]说gensub()
提供了在替换文本中指定regexp组件的能力。这是通过在regexp中使用括号来标记组件,然后在替换文本中指定' N '来完成的。
简而言之,在记录中,我们替换
(anything)total=(interested_value)ending_parenthesis
(interested_value)
并输出结果
使用sed,您可以得到一个更可移植的解决方案:
$ sed -E 's/.*total=(.*))/1/' 38081612
21
28
45
100
Sed还提供了在此处的替换文本(1
)中指定regexp组件的能力。