Question

I have the following info coming into :

Dec  1 23:59:08 ftp1 ftpd[4682]: FTP LOGIN FROM 192.168.0.1 [192.168.0.1], prd
Dec  1 23:59:10 ftp1 ftpd[4690]: FTP LOGIN FROM 192.168.0.2 [192.168.0.2], prod1

I'm trying to get the number between the "[ ]" but only the first set, so in the first line I want 4682 and then have it go to the next line to find the next one. I have the following code but currently it's matching both sets per line, so i"m getting 4682 and 192.168.0.1. How would I go down to the next line after I'm done matching the first

$/ = "\]";

while (my $line = <INPUT>) {
    $line =~ /\[(.*)\]/s;
    my $contents = $1;
    print $contents, "\n";
}

Thank you

Était-ce utile?

La solution

Don't change your input record separator $/ = "\]";, then you can rely on the fact that your first group is the first in the line.

Additionally, if your first group is always enclosed in ftpd[], then you can make your regex more restrictive just in case:

use strict;
use warnings;

while (<DATA>) {
    if (/ftpd\[(.*?)\]/) {
        print "$1\n";
    }
}

__DATA__
Dec  1 23:59:08 ftp1 ftpd[4682]: FTP LOGIN FROM 192.168.0.1 [192.168.0.1], prd
Dec  1 23:59:10 ftp1 ftpd[4690]: FTP LOGIN FROM 192.168.0.2 [192.168.0.2], prod1

Outputs:

4682
4690

Autres conseils

I find it easier to go in two intelligible steps!

#!/usr/bin/perl
use strict;
use warnings;

while (my $line = <>) {
    $line =~ s/\]:.*//;    # Lose ]: and everything after
    $line =~ s/.*\[//;     # Lose [  and everything before
    print $line;
}
4682
4690

Use a regex that looks for exactly what you want, that is:

  • anything
  • followed by an open bracket
  • followed by a digit, one or more times
  • followed by a close bracket
  • followed by anything

Capture the digits.

Here is a sample, notice the regex below... I always use m{} for my regex with xms modifiers, but that should not change anything...

    #!/usr/bin/perl -w
    use strict;

    while (my $line = <>) {
        chomp $line;
        if ($line =~ m{.+\[(\d+)\].+}xms) {
            my $process_id = $1;
            print "Process ID: $process_id\n";
        }
    }

David

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top