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.


In reply to Re: How to grep matching IP address from a log file? by haukex
in thread How to grep matching IP address from a log file? by dotowwxo

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.