user9013730
user9013730

Reputation:

grep cisco interfaces without any configuration

This is sample of Cisco Switch configuration file. If the interface is not in use, it should be in shutdown mode.

config.txt

!
interface GigabitEthernet0/0
 shutdown
!
interface GigabitEthernet0/1
!
interface GigabitEthernet0/2
 shutdown
!
interface GigabitEthernet0/3 
!

Therefore, I would like to grep any interfaces without any configuration and no shutdown in it.

Desired Output

!
interface GigabitEthernet0/1
!
!
interface GigabitEthernet0/3 
!

Can I do something like grep interface.*[0-9] config.txt where the line before and after it must match !

Here are a few of my attempts, but none of them producing the output that I wanted.

grep interface.*[0-9] config.txt
grep -C1 interface.*[0-9] config.txt

If there is a better solution then grep, please let me know.

Upvotes: 1

Views: 223

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627335

I suggest using a GNU grep (or pcregrep if you have no access to GNU grep) solution:

grep -Poz '(?m)^!\R\Kinterface.*\R(?=!$)' file

See the online grep demo and the regex demo.

Details

  • -Poz - P enables the PCRE regex engine to handle the regex, o forces to output just matching text and z enables grep to work with patterns matching across line breaks
  • (?m)^!\R\Kinterface.*\R(?=!$) matches:
    • (?m) - a modifier making ^ match start of lines and $ match end of lines
    • ^ - start of a line
    • ! - a ! char
    • \R - a line break sequence
    • \K - match reset operator that omits all the text matched so far in the current matched text buffer
    • interface - a word
    • .* - the rest of the line
    • \R - a line break sequence
    • (?=!$) - a positive lookahead that makes sure there is a ! char followed with the end of line.

Upvotes: 0

Related Questions