文件中的行评估

文件中的行评估

我有一个这样的源文件:

server1 Mitigated Vulnerable Mitigated
server2 Vulnerable Vulnerable Mitigated
server3 Mitigated Vulnerable Vulnerable
server4 Mitigated Vulnerable Mitigated
server5 Mitigated Vulnerable Mitigated
server6 Vulnerable Vulnerable Vulnerable

我想比较每行的第二个和第四个元素,并按照以下逻辑添加第五个元素:

如果其中一个(第二个或第四个元素)表示易受攻击 - 第五个元素将是易受攻击的(并且我希望将其打印在同一行中,如下所示:

server2 Vulnerable Vulnerable Mitigated Vulnerable

如果仅两个(第二个和第四个)都得到缓解 - 那么第五个元素将得到缓解

您可以忽略第三个元素。

答案1

使用awk

awk '$2 == "Vulnerable" || $4 == "Vulnerable" { $5 = "Vulnerable" } { print }' file

在示例数据上使用它时的结果:

server1 Mitigated Vulnerable Mitigated
server2 Vulnerable Vulnerable Mitigated Vulnerable
server3 Mitigated Vulnerable Vulnerable Vulnerable
server4 Mitigated Vulnerable Mitigated
server5 Mitigated Vulnerable Mitigated
server6 Vulnerable Vulnerable Vulnerable Vulnerable

awk代码查看第二个和第四个字段,如果其中任何一个字段恰好是字符串,Vulnerable则会引入第五个字段。然后打印所有字段(所有输入行)。

答案2

Awk解决方案:

对于这两个条件:

  • 如果其中之一(第二个或第四个元素)说vulnerable- 第五个元素将是Vulnerable
  • 如果只有两个(第二个和第四个)都是mitigated- 那么第五个元素将是Mitigated

awk '$2$4 ~ /[vV]ulnerable/{ $5="Vulnerable" }
     $2 ~ /[mM]itigated/ && $2 == $4{ $5="Mitigated" }1' file

输出:

server1 Mitigated Vulnerable Mitigated Mitigated
server2 Vulnerable Vulnerable Mitigated Vulnerable
server3 Mitigated Vulnerable Vulnerable Vulnerable
server4 Mitigated Vulnerable Mitigated Mitigated
server5 Mitigated Vulnerable Mitigated Mitigated
server6 Vulnerable Vulnerable Vulnerable Vulnerable

相关内容