David Allen
David Allen

Reputation: 760

How can I remove IP addresses from a log file in Perl?

I want to replace a specific amount of text after searching for something with the /s function in perl

libpc07 (158.136.80.63) connect to service annek initially as user annek (uid=7186 gid=199) (pid 6117)

This is the string that I have and I want to search for "(" and deleted 15 digits after this to delete the IP address, I also want to do this with the UID afterwords.

The way that I think it is supposed to work is $newvar =~ s/\(\d{15}//g; but it does not work. I want the text to look like this:

libpc07 connect to service annek initially as user annek

Upvotes: 1

Views: 774

Answers (4)

Leonardo Herrera
Leonardo Herrera

Reputation: 8406

This regex will remove anything that resembles an IP address between parenthesis.

$line =~ s/\((?:[0-9]{1,3}\.){3}[0-9]{1,3}\) //;

999.999.999.999 is not a valid IP address but it will get removed anyways.

Edit: the title of this question is quite misleading. The OP should accept Michael's answer.

Upvotes: 0

Sinan Ünür
Sinan Ünür

Reputation: 118128

Per @jwd's comment, make sure you are only removing IPv4 addresses.

#!/usr/bin/env perl

use warnings; use strict;
use Regexp::Common qw/net/;

while (my $line = <DATA>) {
    $line =~ s!\($RE{net}{IPv4}\) !!;
    print $line;
}

__DATA__
libpc07 (158.136.80.63) connect to service annek initially as user annek (uid=7186 gid=199) (pid 6117)

Upvotes: 4

jwd
jwd

Reputation: 11114

Not really an answer, but your question is a little questionable (:

I doubt you actually care that it is exactly 15 digits.

Suppose the input were ...(111.222.333.444)... or suppose it were ...(1.2.3.4).... You don't really want to remove exactly 15 digits, you want to remove "things that look like IP addresses"

Similar holds true for your removal of UIDs, etc.

Michael's answer will get rid of everything that is surrounded by parentheses, which may be what you want.

Upvotes: 1

Michael Goldshteyn
Michael Goldshteyn

Reputation: 74360

The substitution code would look like:

$newvar =~ s/\([^)]+\)//g;

You may also want to get rid of any trailing white spaces around deleted text, so as not to get double spaces where a deletion occurred, in which case it becomes:

$newvar =~ s/\([^)]+\)\s*//g;

Upvotes: 2

Related Questions