[英]Awk print matched column if exists else print not found
我的文本文件如下所示
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
使用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
输入项
$ 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
每当输入中包含“名称=值”对时,最好首先创建这些映射的数组(下面的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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.