adam.lapins has asked for the wisdom of the Perl Monks concerning the following question:

Hey, I am kind of new to Perl and am trying to right a script that goes through a huge text file and masks IP addresses. I have it working so far that it will mask the first IP in the line, but can't quite get it to mask all ips in the line. Example file might be
set something 111.111.111.111 255.255.255.0
the code that I am using is
if (/\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}/){ s/\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}/xxx.xxx.xxx.xxx/; print VPNOUTFILE "$_"; }
The output that I am getting would be like
set something xxx.xxx.xxx.xxx 255.255.255.0
The output that I am looking for is
set something xxx.xxx.xxx.xxx xxx.xxx.xxx.xxx
Appreciate the help!

Replies are listed 'Best First'.
Re: Masking IPs
by gellyfish (Monsignor) on Jun 28, 2005 at 22:07 UTC

    Use the g (think global) modifier on the substitution and then it will do it more than once :-)

    /J\

Re: Masking IPs
by ikegami (Patriarch) on Jun 28, 2005 at 22:08 UTC
    Add /g:
    if (/\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}/){ s/\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}/xxx.xxx.xxx.xxx/g; print VPNOUTFILE "$_"; }

    The original and the above are redundant, though. You could simply use:

    if (s/\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}/xxx.xxx.xxx.xxx/g) { print VPNOUTFILE "$_"; }

    Are you sure you need to specify \d{1,3}? The following is somewhat easier to read:

    if (s/\d+\.\d+\.\d+\.\d+/xxx.xxx.xxx.xxx/g) { print VPNOUTFILE "$_"; }

      The /g is what the OP wanted. But for the pattern, even better, use a well-crafted regex for IP addresses:

      use Regexp::Common qw(net); print VPNOUTFILE if s/$RE{net}{IPv4}/xxx.xxx.xxx.xxx/g;
Re: Masking IPs
by GrandFather (Saint) on Jun 28, 2005 at 22:54 UTC

    or a "one liner" with strict matching

    use strict; while (<DATA>) { print "$_" if s/(?:\b\d{1,3}\.){3}\d{1,3}\b/xxx.xxx.xxx.xxx/g; }

    Perl is Huffman encoded by design.
Re: Masking IPs
by fmerges (Chaplain) on Jun 28, 2005 at 22:15 UTC

    Hi,

    Also take a look at perlre

    Regards ;-)