首页 > 解决方案 > 只需要 grep IP 地址

问题描述

nslookup google.com
Server:         xx.xx.xx.xx
Address:        xx.xx.xxx.xx#53

Non-authoritative answer:
Name:   google.com
Address: 172.217.164.110

我只需要最后一个带有 grep/awk 的 IP 地址,如下所示,请帮忙。

172.217.164.110

标签: shellgrep

解决方案


可以增强,但它会做你想做的事:

nslookup google.com | sed -n '/Name:/{x;n;p;d;}; x' | awk '{print $2}'

输出(当 nslookup 只返回一个 Name+Address 块时):

172.217.164.110

我使用了 sed 的模式空间高级选项,打印“名称:google.com”行之后的行(x;n;p;“名称:”模式匹配之后的序列)。我不是 sed 大师,我使用了这个 Unix Stack Exchange 答案,然后 awk 只获取空格后面的 IP。在 IPv6 设置中,您可以在两行中同时获取 IPv4 和 IPv6 地址,因此,如果这不是您想要的,您将不得不使用仅匹配 IPv4 格式的模式过滤掉 IPv6。


推荐阅读