in reply to How to grep matching IP address from a log file?
You could use Regexp::Common::net - this will extract any IP's from the line:
use warnings; use strict; use Regexp::Common qw/net/; my $regex = qr{ (?<ip> \b $RE{net}{IPv4} \b ) }msx; my $filename = 'mylogFile.log'; open my $fh, '<:encoding(UTF-8)', $filename or die "$filename: $!"; while (my $line = <$fh>) { while ($line=~/$regex/g) { print "<", $+{ip}, ">\n"; } } close $fh;
However, in your sample input you wrote <my source IP>. If this is an actual IP address, then that will be matched too. If you don't want that, you need to extend the regex to match the surrounding parts of the line. Also, if that's the case, you haven't shown what the actual lines look like, i.e. your input isn't representative, so we can't really help there. All I can say is that if you only want to match one IP per line, you can replace the inner while loop with a single if. Have a look at this for some advice on designing regexes.
In the code you posted, you are reading the entire file into an array, which is a bit wasteful, and it'd probably be better if you used a regular while (<$fh>) loop instead, like what I showed above and as is explained in e.g. Files and I/O and I/O Operators. Also, note that with your current regex, you're just matching the first digits of an IP address, and you may get false positives.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: How to grep matching IP address from a log file?
by dotowwxo (Acolyte) on Dec 19, 2017 at 08:19 UTC | |
by haukex (Archbishop) on Dec 19, 2017 at 13:18 UTC | |
by hippo (Archbishop) on Dec 19, 2017 at 09:02 UTC |