I have an awk statement in a ksh script that looks for a certain string then looks at each line after to find another match. The match could be the next line or second down and it works well.
I am writing a perl script that I need to capture the same kind of match, but I can not find out how to find the string then look at the next lines until the second match is found. I have put together this together but it only looks at the second line after the string is found, which is where my data is usually but sometimes it is on the first next line.
my $loopback = "interface loopback0 ";
foreach my $host (@HOST){
my $out_fh = "$CONFIG_DIR/$host";
open (FILE, "<$out_fh") or die "Can't open $out_fh";
my @lines = <FILE>;
my $lines; my $i;
for $i(0..$#lines) {
next unless $lines[$i] =~ /$loopback/;
my $a = $i + 2 < 0 ? 0 : $i + 2;;
for $i($a) {
if ($lines[$i] =~ /ip address/) {
my ($out) = (split / /, $lines[$i])[4];
$out = (split /\//, $out)[0];
print "$out\n";
}
}
}
}
close (FILE);
Can someone help me find something that works?
A file example of what the first string finds is like this:
!
interface loopback0 loopback
description My Router Loopback
ip address 10.30.160.10/32 tag 200
ip source-address tftp ftp
!
interface loopback1 loopback
description External BGP
ip address 10.159.192.9/32 tag 201
!
interface loopback2 loopback
ip address 10.159.168.33/32 tag 202
ip source-address radius
!
interface loopback3 loopback
description ID: Management;
ip address 10.81.114.6/32 tag 203
ip source-address snmp syslog
!
NAME
a2p - Awk to Perl translator
SYNOPSIS
a2p [options] [filename]
DESCRIPTION
A2p takes an awk script specified on the command line (or from standard
input) and produces a comparable perl script on the standard output.
Thank you for replying, but I was looking for a code that did not include awk. I am new to perl and know it is very rich, so I believe this can be done strictly in perl.
I made some updates to the script and it works, may not very beautiful, but it does what I need to look at the first and second line after the string match.
foreach my $host (@HOST){
my $out_fh = "$CONFIG_DIR/$host";
open (FILE, "<$out_fh") or die "Can't open $out_fh";
my @lines = <FILE>;
my $lines; my $i;
for $i(0..$#lines) {
next unless $lines[$i] =~ /$loopback/;
my $a = $i + 1 < 0 ? 0 : $i + 1;;
my $b = $i + 2 < 0 ? 0 : $i + 2;;
for $i($a) {
if ($lines[$i] =~ /ip address/) {
my ($out) = (split / /, $lines[$i])[4];
$out = (split /\//, $out)[0];
print "$out\n";
}
}
for $i($b) {
if ($lines[$i] =~ /ip address/) {
my ($out) = (split / /, $lines[$i])[4];
$out = (split /\//, $out)[0];
print "$out\n";
}
}
}
close (FILE);
}