Warm tip: This article is reproduced from stackoverflow.com, please click
awk regex ubuntu

regular expression to select particular word when it is not followed by particular pattern?

发布于 2020-04-07 10:22:17

I have a list of the data in this format:

eth0: flags=73<UP,LOOPBACK,RUNNING>  mtu 1500
    inet 127.0.0.1  netmask 255.0.0.0
    inet6 ::1  prefixlen 128  scopeid 0xfe<compat,link,site,host>
    loop  (Local Loopback)
    RX packets 0  bytes 0 (0.0 B)
    RX errors 0  dropped 0  overruns 0  frame 0
    TX packets 0  bytes 0 (0.0 B)
    TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

eth1: flags=73<UP,LOOPBACK,RUNNING>  mtu 1500
    inet6 ::1  prefixlen 128  scopeid 0xfe<compat,link,site,host>
    loop  (Local Loopback)
    RX packets 0  bytes 0 (0.0 B)
    RX errors 0  dropped 0  overruns 0  frame 0
    TX packets 0  bytes 0 (0.0 B)
    TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

I need to select eth1 (which is the first word and it is a word which always starts with e) it is not followed by 127.0.0.1 (which could also appear later in the following line).

here eth0 is not qualified because it is followed by 127.0.0.1

I tried everything and nothing seems to work. is it even possible with a regular expression? if yes then how?

Questioner
rahul Kushwaha
Viewed
69
MonkeyZeus 2020-02-01 04:28

Not sure about the Ubuntu implementation details but you can make use of a negative lookahead:

^eth\d+(?=:)(?!.*\n.*[^0-9]127\.0\.0\.1[^0-9])
  • ^eth\d+(?=:) - the start of the line must be "eth", followed by one or more digits, and followed by a colon but do not capture the colon
  • (?!.*\n.*[^0-9]127\.0\.0\.1[^0-9]) - make sure that the contents which follow the previous match do not contain "127.0.0.1"

https://regex101.com/r/NeEAnn/1