我使用“ip a”和“sed”管道来显示所有接口的 IP 地址:
ip a |sed -En "{N ; N ; s/^[1-9]: (.*: ).+\n?.+\n? {4}inet \
(([0-9]{1,3}[./]){4}[0-9]{1,2}).*/\1\2/p}"
为什么我不能替换组
(([0-9]{1,3}[./]){4}[0-9]{1,2})
与 (.*\ ) 并改为写入
ip a |sed -En "{N ; N ; s/^[1-9]: (.*?: ).+\n?.+\n? {4}inet \
(.*\ ).*/\1\2/p}"
它匹配,但仅在行尾找到 ip 地址后面的空白,从而将整行打印为 \2。在“正常”正则表达式中,这是有效的。
ip a 的输出为:
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000
link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
inet 127.0.0.1/8 scope host lo
valid_lft forever preferred_lft forever
inet6 ::1/128 scope host
valid_lft forever preferred_lft forever
2: eno1: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP group default qlen 1000
link/ether 10:78:d2:8e:e7:cf brd ff:ff:ff:ff:ff:ff
inet 192.168.1.44/24 brd 192.168.1.255 scope global dynamic eno1
valid_lft 41778sec preferred_lft 41778sec
inet6 fe80::1278:d2ff:fe8e:e7cf/64 scope link
valid_lft forever preferred_lft forever
3: wlx68a3c45b2875: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP group default qlen 1000
link/ether 68:a3:c4:5b:28:75 brd ff:ff:ff:ff:ff:ff
inet 192.168.1.36/24 brd 192.168.1.255 scope global dynamic noprefixroute wlx68a3c45b2875
valid_lft 40457sec preferred_lft 40457sec
inet6 fe80::6aa3:c4ff:fe5b:2875/64 scope link
valid_lft forever preferred_lft forever
答案1
要匹配字符串直到空格,请使用[^ ]*
完整的命令为:
ip a |sed -En "{N ; N ; s/^[1-9]: (.*: ).+\n?.+\n? {4}inet \
([^ ]*).*/\1\2/p}"
输出:
lo: 127.0.0.1/8
eno1: 192.168.1.44/24
wlx68a3c45b2875: 192.168.1.36/24