与字符串中的 sed 正则表达式匹配

Match with sed regex in string

我想用 sed 和正则表达式匹配 stdout 命令中的字符串

例如我有这个输出命令:connmanctl services ethernet_00142d000000_cable

此输出:

Type = ethernet
  Security = [  ]
  State = ready
  Favorite = True
  Immutable = False
  AutoConnect = True
  Name = Wired
  Ethernet = [ Method=auto, Interface=eth0, Address=00:00:00:00:00:00, MTU=1500 ]
  IPv4 = [ Method=manual, Address=192.168.0.100, Netmask=255.255.255.0 ]
  IPv4.Configuration = [ Method=manual, Address=192.168.0.101, Netmask=255.255.255.0 ]
  IPv6 = [  ]
  IPv6.Configuration = [ Method=auto, Privacy=disabled ]
  Nameservers = [  ]
  Nameservers.Configuration = [  ]
  Timeservers = [  ]
  Timeservers.Configuration = [  ]
  Domains = [  ]
  Domains.Configuration = [  ]
  Proxy = [ Method=direct ]
  Proxy.Configuration = [  ]
  Provider = [  ]

我想从 Interface=eth0,(第 8 行)中获取 eth0

所以我使用这个命令:services ethernet_00142d000000_cable | sed -n -e 's/^.*Ethernet = //p' | sed -e 's/.*Interface=\([^,*]*\),*//'

第一个 sed 提取整行以太网,第二个 sed 提取以 Interface 开头并以逗号结尾的字符串。

结果是:

eth0 Address=00:14:2D:00:00:00, MTU=1500 ]

为什么我在逗号后得到了以下内容。我怎样才能得到 eth0 ?

谢谢。

重定向输出:

eth0 Address=00:14:2D:00:00:00, MTU=1500 ]

到 awk 如:

services ethernet_00142d000000_cable | sed -n -e 's/^.*Ethernet = //p' | sed -e 's/.*Interface=\([^,*]*\),*//' > awk 'BEGIN { FS = " ";}{print ;}'
$ echo 'Ethernet = [ Method=auto, Interface=eth0, Address=00:00:00:00:00:00, MTU=1500 ]' | sed -e 's/.*Interface=\([^,]*\),*//'
eth0 Address=00:00:00:00:00:00, MTU=1500 ]

您的正则表达式有 [^,*]*,效果不佳。将其替换为 [^,]*,读作“零个或多个不是逗号的字符”。

如果你只想要 eth0 而没有别的,那么使用:

$ echo 'Ethernet = [ Method=auto, Interface=eth0, Address=00:00:00:00:00:00, MTU=1500 ]' | sed -e 's/.*Interface=\([^,]*\).*//'
eth0

我认为你用 ,* 而不是 .* 来匹配任何内容。

下面是如何使用单个 sed 命令将您的编辑定位到特定行:

services ethernet_00142d000000_cable | \
      sed -n -e '/Ethernet =/s/.*Interface=\([^,]*\).*//p'

明白了吗?您可以通过在 s/// 命令之前添加模式(甚至是行范围规范)来限制它。