-1

I would like to know if have some Sed/Grep or Awk regex to parse Cisco interface section, with specific attribute, like bellow.

Content of file.txt

!
interface FastEthernet0/1
 no ip unreachables
!
interface FastEthernet0/2
 no ip proxy-arp
!

Script:

#!/bin/bash
VALUE="no ip proxy-arp"
awk -v RS='!\n' -v PATTERN=${VALUE} '/$PATTERN/' file.txt | awk '/^interface/';
exit 0

The problem is when I run line directly from shell, it work, but when I run from script, it don't work.

Running with bash -x, I can see that awk can't replace variable value.

Any suggestions ?

  • Something like grep -B1 'no ip proxy-arp' file.txt | head -1? What is the expected output? – Teresa e Junior Apr 12 '13 at 3:16
  • @TeresaeJunior I don't know whether this is necessary but the awk solutions deliver (possibly) more than one line. Thus the second part of the pipeline should be e.g. another grep. – Hauke Laging Apr 12 '13 at 4:07
  • 1
    FYI, you asked for sed|grep|awk assistance; however, ciscoconfparse is a python module which specializes in handling these kind of tasks. If you do a lot of this, it may be worth your while to consider using a library which is built for parsing cisco configs. – Mike Pennington Feb 8 '14 at 19:31
3

Hard to believe that this works in your shell. Nonetheless this code contains several errors and also has the wrong approach IMHO.

awk expects a string between // not a variable. These are constant regular expressions. So you either make the shell put the variable there or you use ~.

Your approach with corrections:

awk -v RS='!\n' -v PATTERN="${VALUE}" '$0 ~ PATTERN' file.txt | 
  awk '/^interface/'

I am surprised that this works. From the documentation I had expected that due to the setting of RS an unwanted "!" would be printed. However, I consider this one better:

awk -v PATTERN="${VALUE}" \
  '$0 ~ PATTERN { print previousline; }; { previousline=$0; }' file.txt

or with hardcoded pattern

awk '/no ip proxy-arp/ { print previousline; }; { previousline=$0; }' file.txt

or with the shell writing the pattern

awk /"$VALUE"/' { print previousline; }; { previousline=$0; }' file.txt
-1
echo "!
interface FastEthernet0/1
 no ip unreachables
!
interface FastEthernet0/2
 no ip proxy-arp
"  | pcregrep -M "^interface .*0/1\n (.*\n)!"

result:

interface FastEthernet0/1
 no ip unreachables
  • The OP only wants to show interfaces containing the text no ip proxy-arp, and your command doesn't check for that. Your result only shows one section (the wrong one) because you've omitted the ! from the end of the input. – JigglyNaga Dec 10 '18 at 10:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.