【问题标题】:Match with sed regex in string与字符串中的 sed 正则表达式匹配
【发布时间】:2020-11-14 02:20:03
【问题描述】:

我想用 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=\([^,*]*\),*/\1/'

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

结果是:

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

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

谢谢。

【问题讨论】:

    标签: regex linux sed match comma


    【解决方案1】:

    重定向输出:

    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=\([^,*]*\),*/\1/' > awk 'BEGIN { FS = " ";}{print $1;}'
    

    【讨论】:

      【解决方案2】:
      $ echo 'Ethernet = [ Method=auto, Interface=eth0, Address=00:00:00:00:00:00, MTU=1500 ]' | sed -e 's/.*Interface=\([^,]*\),*/\1/'
      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=\([^,]*\).*/\1/'
      eth0
      

      我认为您在匹配任何内容时使用了 ,* 而不是 .* 的拼写错误。

      【讨论】:

        【解决方案3】:

        以下是使用单个 sed 命令将编辑定位到特定行的方法:

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

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

        【讨论】:

        • 哦,它工作得非常好,并且带有信号线更好。谢谢
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-01-17
        • 2019-05-01
        • 2013-10-18
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多