Help with regex in Shell script

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

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

interface Serial1/0
Description serial interface
ip address 25.10.8.120 255.255.255.224


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`
do

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

done

This give me something like:
myrouter10
myrouter1
ip address 10.15.28.10 255.255.255.252
myrouter25
etc, etc

But I need something like this:

myrouter1
interface GigabitEthernet2/1/1.23
ip address 10.15.28.10

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 •

#1
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
          pinterface=1
          }

       if($0 ~ /^interface/ && pinterface == 1)
          {
          print $0
          pinterface=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