使用 grep 从横幅中获取 IP 和端口

using grep to get IP and Port out of a banner

我有一个横幅列表,格式如下:

Hostname: []
IP: xxx.xxx.xxx.xxx
Port: xx
HTTP/1.0 301 Moved Permanently
Location: /login.html
Content-Type: text/html
Device-Access-Level: 255
Content-Length: 3066
Cache-Control: max-age=7200, must-revalidate

为了抓取 ip,我使用了下面的 grep 语句:

grep -E -o "([0-9]{1,3}[\.]){3}[0-9]{1,3}"

我还必须在语句中添加什么才能获取端口? (同时仍然获得 IP。)。

感谢您的回答..!

为什么不用awk

awk '/IP:/ {ip=} /Port:/ {print ip,}' file

当它找到包含 IP: 的行时,它会将 IP 存储在变量 ip
中 当它找到端口时,打印 ip 和端口号。


例子

cat file
Hostname: []
IP: 163.248.1.20
Port: 843
HTTP/1.0 301 Moved Permanently
Location: /login.html
Content-Type: text/html
Device-Access-Level: 255
Content-Length: 3066
Cache-Control: max-age=7200, must-revalidat

awk '/IP:/ {ip=} /Port:/ {print ip,}' file
163.248.1.20 843