Take the tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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 ?

share|improve this question
 
Something like grep -B1 'no ip proxy-arp' file.txt | head -1? What is the expected output? –  Teresa e Junior Apr 12 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 at 4:07
add comment

1 Answer

up vote 2 down vote accepted

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
share|improve this answer
 
+1 for previousline. Nice one :) –  Teresa e Junior Apr 12 at 5:11
 
Thank you Hauke, the first approach above work fine. –  Robert Apr 12 at 18:34
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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