RegExp Filter: Extract complete interface blocks without ‘shutdown’ statement
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:
no ip address
And here the same again without the ‘stutdown’ statement:
no ip address
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:
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:
This will return just the matches for interfaces in ‘no shutdown’ state.