簡體   English   中英

與字符串中的 sed 正則表達式匹配

[英]Match with sed regex in string

我想將 stdout 命令中的字符串與 sed 和正則表達式匹配

例如,我有這個 output 命令: connmanctl services ethernet_00142d000000_cable

這個 output:

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, eth0第 8 行)。

所以我使用這個命令: services ethernet_00142d000000_cable | sed -n -e 's/^.*Ethernet = //p' | sed -e 's/.*Interface=\([^,*]*\),*/\1/' 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

謝謝你。

以下是如何使用單個 sed 命令將您的編輯定位到特定行:

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

得到它? 您可以通過在s///命令之前添加模式(甚至是行范圍規范)來限制它。

重定向 output:

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;}'
$ 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

我認為您使用,*而不是.*拼寫錯誤以匹配任何內容。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM