我的文本文件如下所示
date="2017-10-10" ip=192.168.1.1:22 inbound=100 outbound=100
date="2017-10-10" ip=192.168.1.1:22 inbound=100
date="2017-10-10" ip=192.168.1.1:22 outbound=100
我使用下面的awk代码打印匹配的字符串,并提取"=“后面的任何内容。
awk '{for(i=1;i<=NF;i++)if($i~/inbound=/)print $(i)}' | cut -d : -f1 | cut -d = -f2
例如,我会搜索"inbound=“并提取"100”。但棘手的部分是“入站”不会在文本的所有行,现在我想打印"0“,如果一行没有”入站“。
预期输出
100
100
0 Not Found
发布于 2017-06-02 06:12:18
每当输入中有name=value对时,最好首先创建这些映射的数组(下面是f[]
),然后只需按名称打印(或使用其他任何操作)值:
$ awk -v n="inbound" -F'[ =]+' '{delete f; for (i=1;i<NF;i+=2) f[$i]=$(i+1); print (n in f ? f[n] : "0 Not Found")}' file
100
100
0 Not Found
要对“出站”或任何其他字段执行同样的操作吗?只需相应地插入名称变量n
“
$ awk -v n="outbound" -F'[ =]+' '{delete f; for (i=1;i<NF;i+=2) f[$i]=$(i+1); print (n in f ? f[n] : "0 Not Found")}' file
100
0 Not Found
100
$
$ awk -v n="date" -F'[ =]+' '{delete f; for (i=1;i<NF;i+=2) f[$i]=$(i+1); print (n in f ? f[n] : "0 Not Found")}' file
"2017-10-10"
"2017-10-10"
"2017-10-10"
$
$ awk -v n="ip" -F'[ =]+' '{delete f; for (i=1;i<NF;i+=2) f[$i]=$(i+1); print (n in f ? f[n] : "0 Not Found")}' file
192.168.1.1:22
192.168.1.1:22
192.168.1.1:22
发布于 2017-06-02 03:43:08
使用GNU awk
awk '{print match($0,/inbound=([0-9]+)/,a)?a[1]:0}' file
在perl中
perl -lne 'print /inbound=(\d+)/?$1:0' file
在sed中
sed 's/.*inbound=\([0-9]\+\).*/\1/;t;s/.*/0/' file
发布于 2017-06-02 03:31:19
输入
$ cat file
date="2017-10-10" ip=192.168.1.1:22 inbound=100 outbound=100
date="2017-10-10" ip=192.168.1.1:22 inbound=100
date="2017-10-10" ip=192.168.1.1:22 outbound=100
输出
$ awk '{if(match($0,/inbound=[0-9]+/)){s=substr($0,RSTART,RLENGTH); print substr(s,index(s,"=")+1);next}print 0,"Not Found"}' file
100
100
0 Not Found
解释
awk '{
# Search for word inbound=[0-9]+ in record/line/row, if found then
if(match($0,/inbound=[0-9]+/))
{
# Extract word
s=substr($0,RSTART,RLENGTH)
# Print value which is after "="
print substr(s,index(s,"=")+1)
# Go to next line
next
}
# If above condition is not true then word inbound not found in line/row/record
print 0,"Not Found"
}
' file
https://stackoverflow.com/questions/44327731
复制相似问题