我的文字文件如下所示
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
答案 0 :(得分:2)
使用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
答案 1 :(得分:1)
<强>输入强>
$ 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
答案 2 :(得分:1)
每当你的输入中有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
想要为&#34;出境&#34;做同样的事情。或任何其他领域?只需相应地初始化名称变量n
&#34;
$ 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