RegExp Filter: Extract complete interface blocks without ‘shutdown’ statement

Posted by: gdelmatto  :  Category: Cisco, Networking, Programming, RegExp

A project I’m currently working on involges much Regurlar Expressions trickery to parse values from Cisco’s running configuration.
Here’s how to extract a complete interface block not in ‘shutdown’ state.

Imagine a Cisco configuration block like this:


!
interface BRI0
no ip address
encapsulation hdlc
shutdown
!

And here the same again without the ‘stutdown’ statement:


!
interface BRI0
no ip address
encapsulation hdlc
!

Thinking about a case where you want to extract just these blocks from multiple config files, but only if they don’t contain the ‘shutdown’ statement. The solution to this with Regular Expressions is called negative look-ahead, so to speak “match something not followed by something else”.

The trick is to make anchored matches within the context we’re searching.
Looking at the block, we get multiple anchors:

  • ‘interface’ following by the interface name and line feed/carriage return as our beginning marker
  • a line starting with an exclamation mark marking the end of the block
  • any number of lines in between starting with at least 1 whitespace character

So an extended expression, which would match just this criteria looks like this:

/^interface .*[\r\n]+(?:^\s.*[\r\n])+(?:^![\r\n]+)+/m

This would match any interface configuration block.
Now if we want only the interface in ‘no shutdown’ state, we add a negative look-ahead which can be spoken of as this:

  • any number of lines in between starting with at least 1 whitespace character NOT followed by the word ‘shutdown’

Thus, our expression now looks like this:

/^interface .*[\r\n]+(?:^\s(?!shutdown).*[\r\n])+(?:^![\r\n]+)+/m

This will return just the matches for interfaces in ‘no shutdown’ state.

Comments are closed.