TransWikia.com

Match with sed regex in string

Stack Overflow Asked by Tupperware on December 25, 2021

I want to match a string in a stdout command with sed and regex

For example i have for this output command : connmanctl services ethernet_00142d000000_cable

this 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 = [  ]

I want to get eth0 from Interface=eth0, (line 8).

so i use this command : services ethernet_00142d000000_cable | sed -n -e 's/^.*Ethernet = //p' | sed -e 's/.*Interface=([^,*]*),*/1/'

The first sed to extract the entire line with Ethernet and the second sed to extract the string beginning with Interface and end with comma.

and the result is :

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

Why i got already the following after the comma. how can i get only eth0 ?

Thank you.

3 Answers

And here's how to target your edit to a particular line, with a single sed command:

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

Get it? You can restrict the s/// command by adding a pattern (or even a line range specification) before it.

Answered by alexis on December 25, 2021

$ 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 ]

Your regex had [^,*]*, which doesn't work well. Replaced it with [^,]*, which reads as "zero or more characters that are not a comma".

And if you want only the eth0 and nothing else, then use:

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

I think you had a typo with the ,* instead of .* to match anything.

Answered by kingsindian on December 25, 2021

Redirect the output :

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

to awk such as :

services ethernet_00142d000000_cable | sed -n -e 's/^.*Ethernet = //p' | sed -e 's/.*Interface=([^,*]*),*/1/' > awk 'BEGIN { FS = " ";}{print $1;}'

Answered by Farhad Sarvari on December 25, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP