Reputation: 5146
I have this output from router command:
Interface IP-Address OK? Method Status Protocol
POS0/0/0 10.137.99.2 YES NVRAM up up
I want to find a regular expression to identify the IP-Address:
I tried with:
if ( $_ =~ m/(.*?)\s*?(.*?)\s*?(.*?)\s*?(.*)/i ){
#print "$1->$2\n";
$sources{$2}=$1;
}
and then use $2
as ip.
However, it does not work; where am I wrong?
Upvotes: 1
Views: 1067
Reputation: 4048
if ($_ =~ /\b(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})\b/)
{
print "IP: $1\n";
}
If you just want to obtain the second column, then may be you should use split
instead of regular expressions. To obtain field #2:
@field = split(/ +/, $_);
print "$field[1]";
Upvotes: 6
Reputation: 701
Since this is regularly formatted data, you could probably just use split: and get at it like this:
#!/usr/bin/env perl
use Modern::Perl;
my $buff = "Interface IP-Address OK? Method Status Protocol
POS0/0/0 10.137.99.2 YES NVRAM up up ";
for my $line (split /\n/,$buff)
{
next if $line =~ /^Interface/;
my ($interface, $ip) = (split /\s+/,$line)[0,1];
say "IP $ip is on Interface $interface";
}
which produces this output:
IP 10.137.99.2 is on Interface POS0/0/0
Upvotes: 2
Reputation: 46667
PacoRG's answer works nicely, but to explain where yours is going wrong:
Remember that *
can match no occurrences. You're telling each group to match as little as possible, so the first 3 groups are capturing nothing. Further, you want to grab as many consecutive whitespace characters as possible, not as few.
Keeping with a RegEx somewhat like your original, you could use
m/(.+?)\s+(.+?)\s+(.+?)\s+(.+?)/i
Upvotes: 2
Reputation: 80384
The bug is all those minimal matches. Just use
($if, $ip) = split;
$sources{$ip} = $if;
Upvotes: 1