![如何对 grep 结果进行分组?](https://linux22.com/image/18189/%E5%A6%82%E4%BD%95%E5%AF%B9%20grep%20%E7%BB%93%E6%9E%9C%E8%BF%9B%E8%A1%8C%E5%88%86%E7%BB%84%EF%BC%9F.png)
我有一个文件,其中包含按类别分组的结果。例如:
checking results for $var
here are some results1 for $var status ok
here are some results2 for $var status ok
here are some results3 for $var status ok
checking results for $var2
here are some results1 for $var2 status ok
checking results for $var3
here are some results1 for $var3 status ok
here are some results2 for $var3 status ok
here are some results3 for $var3 status critical
here are some results4 for $var3 status ok
我需要检查给定类别中的任何行是否具有“关键”状态,如果是,则显示它。例如:
Status $var -- OK
Status $var2 -- OK
Status $var3 -- Critical
Note : Critial at $result3 for $var3
使用grep -A
不太适合我,因为特定变量下的结果数量各不相同。
答案1
awk 会这样做:
awk '
BEGIN {
priority["ok"] = 10
priority["critical"] = 20
}
/^$/ {next}
/^checking/ {var = $NF}
{
if (priority[status[var]] < priority[$NF])
status[var] = $NF
if ($NF == "critical")
crit[var ":" $4] = 1
}
END {
for (var in status)
print var, status[var]
for (c in crit) {
split(c, ary, /:/)
printf("critical at %s for %s\n", ary[2], ary[1])
}
}
'
输出
$var ok
$var2 ok
$var3 critical
critical at results3 for $var3
答案2
我会使用 awk 脚本:
/^checking results for / {
if (curvar) { print curvar, curstatus; }
curvar = $NF
curstatus = "ok"
}
/^here are some results.* for .* status / {
if ($NF != "ok") { curstatus = $NF;
}
END {
if (curvar) { print curvar, curstatus; }
}
您可以使用数组来构建“不良结果”表。