Help with regex in Shell script

February 23, 2011 at 11:34:05
Specs: Solaris 10, 4GB
Need to parse thounsands of files and extract certain lines from each file if some condition is met.
Files has many lines similar to this:

hostname myrouter1
interface GigabitEthernet2/1/1.23
descriptio to my carrier
ip address

interface Serial1/0
Description serial interface
ip address

Need to parse files and if "ip address 10.###.###.###" or "ip address 16.###.###.###" then extract (print) line containing hostname, interface name, and its ip address. Do not care about subnet mask (number following ip address).

So far I have this:

for names in `cat /tmp/cfgnames.txt`

#Only print if got ip address in scope:
nawk ' /^hostname/{print $2}; /^\ \ip address 10/ || /^\ \ip address 16/ ' $names >> /tmp/myrouters.txt


This give me something like:
ip address
etc, etc

But I need something like this:

interface GigabitEthernet2/1/1.23
ip address

for each device that satify my search criteria.
Note: A device can have multiple interfaces that meet search criteria.

Thank you very much for your help.

See More: Help with regex in Shell script

Report •

February 23, 2011 at 12:44:14
First, I dropped the loop to concentrate on the nawk script.

I am assuming that you don't want the myrouter10 because it has no interface or ip address? I can not tell from your data sample.

Anyway, I think this is closer to what you want:

nawk ' BEGIN { pinterface=0 }
       if($0 ~ /^hostname/)
          print $2

       if($0 ~ /^interface/ && pinterface == 1)
          print $0

       if( ($0 ~ /^ip address 10/ ) || ($0 ~ /^ip address 16/) )
          printf("%s %s %s\n", $1, $2, $3)

} ' names.txt
# end script

Let me know if you need more help.

Report •
Related Solutions

Ask Question