Paul Dawson
Paul Dawson

Reputation: 1382

grep with PCRE to return after multiple whitespace occurrences

I am trying to have grep return both interfaces 1/1.2 AND 1/1.6 but I can't find a way to return both, only the first.

net trunk dmz_trunk { bandwidth 20000 cfg-mbr-count 2 id 1 interfaces { 1/1.2 1/1.6 } lacp enabled mac-address f4:15:63:c9:7b:e1 media 10000 working-mbr-count 2 }

I've tried:

grep  -oP '(interfaces {)\s+\K\S+\S+') 

I am getting the first 1/1.2 but not the second 1/1.6

Any ideas with grep or do I need to use awk?

Upvotes: 1

Views: 56

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626689

If you want to further use grep with the PCRE engine you may leverage the \G construct to build a custom left-hand boundary and grab all values you need after interface { and before the next } using

grep  -oP '(?:\G(?!^)|interfaces\s*{)\s*\K[^{}\s]+'

See the grep online demo and the regex demo.

Details

  • (?:\G(?!^)|interfaces\s*{) - either the end of the previous successful match (\G(?!^)) or (|) interfaces, 0+ whitespaces, { (interfaces\s*{)
  • \s* - 0+ whitespaces
  • \K - match reset operator
  • [^{}\s]+ - 1 or more chars other than whitespace, { and }

Upvotes: 1

Related Questions