如果行以特定字符串开头,则使用 awk 仅打印该行中包含的 ip 地址,每行一个

If line starts with a specific string, print only the ip addresses contained within that line using awk, one per line

我使用 awk 解析的命令 (cmdagent -i) 输出了以下文本:

Component: McAfee Agent  
AgentMode: 1  
Version: 5.0.6.491  
GUID: f0bcc8de-1aa6-00a4-01b9-00505af06706  
TenantId: N/A  
LogLocation: /var/McAfee/agent/logs  
InstallLocation: /opt/McAfee/agent  
CryptoMode: 0  
DataLocation: /var/McAfee/agent  
EpoServerList: 10.0.25.15|epo1|epo1.example.com|10.0.25.20|epo2|epo2.example.com 
EpoPortList: 443  
EpoServerLastUsed: 10.0.25.15  
LastASCTime: N/A  
LastPolicyUpdateTime: 0  
EpoVersion: 5.3.1  
Component: McAfee Agent

我想匹配以字符串 "EpoServerList" 开头的行,并仅使用 1 个 awk 命令打印该行中包含的 IP 地址。

如果我使用两个 awk 命令,我可以让它工作,但我知道它可以只用一个。

例如:

# ./cmdagent -i | awk '/^EpoServerList/' | awk -v RS='([0-9]+\.){3}[0-9]+' 'RT{print RT}'

给出以下(期望的)输出:

10.0.25.15
10.0.25.20

到目前为止我已经尝试了以下方法:

# ./cmdagent -i | awk -v RS='([0-9]+\.){3}[0-9]+' '[=13=] ~ /^EpoServerList/ RT{print RT}'

return 没有任何匹配项

./cmdagent -i | awk -v RS='([0-9]+\.){3}[0-9]+' '[=14=] ~ /^EpoServerList/; RT{print RT}'

哪个 return 来自不需要的行的版本号:

 5.0.6.491
 10.0.25.15
 10.0.25.20

并且似乎不考虑“/^EpoServerList/”,我试图将其用作排除包含版本字符串“5.0.6.491”的行的标准

我如何在 EpoServerList 上进行匹配,并且仍然使用带有正则表达式的记录分隔符来仅使用 1 个 awk 语句来匹配和打印 IP 地址?

这是 RHEL 7 x86_64 上的 GNU Awk 4.0.2,使用 bash shell.

首先匹配行,然后遍历匹配 IPv4 模式的字段:

awk -F '[|: ]' '/^EpoServerList: / { for (i=1; i<NF; i++) { if (match($i, "([0-9]+\.){3}[0-9]+")) { print $i; } } }'

使用多个字段分隔符允许将标签视为一列,因此在匹配 IP 地址时会跳过它。

我知道这里有很多人会说 awk > grep + some-other-tool,但我发现这个组合乍看之下产生了更多的可读性:

grep '^EpoServerList: ' | grep -oP '([0-9]+\.){3}[0-9]+'

请注意,-o-p 是 GNU 扩展,我使用它是因为您依赖 RHEL。

awk -F'[ |]' '/EpoServerList/{print "\n"}' file
10.0.25.15
10.0.25.20

您也可以试试这个 Perl 解决方案

$ perl -lne ' if(/EpoServerList/) { while(/\d+.\d+.\d+.\d+/g) { print "$&" } } ' chris_smith.txt
10.0.25.15
10.0.25.20

输入:

$ cat chris_smith.txt
Component: McAfee Agent
AgentMode: 1
Version: 5.0.6.491
GUID: f0bcc8de-1aa6-00a4-01b9-00505af06706
TenantId: N/A
LogLocation: /var/McAfee/agent/logs
InstallLocation: /opt/McAfee/agent
CryptoMode: 0
DataLocation: /var/McAfee/agent
EpoServerList: 10.0.25.15|epo1|epo1.example.com|10.0.25.20|epo2|epo2.example.com
EpoPortList: 443
EpoServerLastUsed: 10.0.25.15
LastASCTime: N/A
LastPolicyUpdateTime: 0
EpoVersion: 5.3.1
Component: McAfee Agent

$