AWK打印匹配的列(如果存在),否则找不到打印 [英] 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代码来打印匹配的字符串,并提取"="之后的内容.
I am using the below awk code to print the matched string and extract whatever is after the "=".
awk '{for(i=1;i<=NF;i++)if($i~/inbound=/)print $(i)}' | cut -d : -f1 | cut -d = -f2
例如,我将搜索"inbound ="并提取"100". 但棘手的部分是入站"不会出现在所有文本行中 现在,如果一行中没有单词"inbound",我想打印"0".
For example I would search for "inbound=" and extract the "100". But the tricky part is "inbound" won't there in all the lines of the text Now I would like to print "0" if a line doesn't have the word "inbound".
预期输出
100
100
0 Not Found
推荐答案
每当输入中包含name = value对时,最好首先创建一个包含这些映射的数组(下面的f[]
),然后就可以打印(或对名称中的值进行其他操作:
Whenever you have name=value pairs in your input it's best to first create an array of those mappings (f[]
below) and then you can just print (or do anything else with) the values by name:
$ 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
"
Want to do the same for "outbound" or any other field? Just init the name variable n
accordingly"
$ 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
这篇关于AWK打印匹配的列(如果存在),否则找不到打印的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!