Mashed Potato has asked for the wisdom of the Perl Monks concerning the following question:
Hello Sirs - please take it easy on me if this is an elementary question, I'm fairly new to Perl. I could not find any relevant topics.
I am trying to define a string from a subset of each line which matches my regex, and then read down in the file to find the other lines which match the string. If there is more than one match, print the number of matches and the lines.
My data:
src=2.2.2.2 dst=1.1.1.1 src_port=50232 dst_port=514 reason=AGE OUT src=2.2.2.2 dst=1.1.1.1 src_port=50232 dst_port=514 reason=Traffic Den +ied src=3.3.3.3 dst=4.4.4.4 src_port=50235 dst_port=123 reason=AGE OUT src=3.3.3.3 dst=4.4.4.4 src_port=50235 dst_port=123 reason=AGE OUT
My attempt seems to only print the first match. Is that because the inside file loop passes EOF to the outside? I believe I have used this before with arrays and it worked, but this file is too large to take into memory.
#!/usr/bin/perl use strict; use warnings; my $file = 'tmpfile'; my $match; my $numelements; open my $info, $file or die "Could not open $file: $!"; while( my $line = <$info>) { if ( $line =~ m/(src\=\d+\.\d+\.\d+\.\d+\sdst\=\d+\.\d+\.\d+\. +\d+\ssrc\_port\=\d+\sdst\_port\=\d+).*AGE OUT/ ) { $match = "$1"; push (my @dups, $line); while( my $twoline = <$info> ) { if ( $twoline =~ /$match/ ) { push @dups, $twoline; } } $numelements = @dups; print "$match has $numelements elements\n"; if ( $numelements > 1 ) { print join("\n", @dups); } } } close $info;
Output I get:
$./tcprst.pl src=2.2.2.2 dst=1.1.1.1 src_port=50232 dst_port=514 has 2 elements src=2.2.2.2 dst=1.1.1.1 src_port=50232 dst_port=514 reason=AGE OUT src=2.2.2.2 dst=1.1.1.1 src_port=50232 dst_port=514 reason=Traffic Den +ied $
Output I expect:
src=2.2.2.2 dst=1.1.1.1 src_port=50232 dst_port=514 has 2 elements src=2.2.2.2 dst=1.1.1.1 src_port=50232 dst_port=514 reason=AGE OUT src=2.2.2.2 dst=1.1.1.1 src_port=50232 dst_port=514 reason=Traffic Den +ied src=3.3.3.3 dst=4.4.4.4 src_port=50235 dst_port=123 has 2 elements src=3.3.3.3 dst=4.4.4.4 src_port=50235 dst_port=123 reason=AGE OUT src=3.3.3.3 dst=4.4.4.4 src_port=50235 dst_port=123 reason=AGE OUT
Thank you in advance
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Define string on current line, then match other lines with string below the line
by GotToBTru (Prior) on Oct 02, 2014 at 18:27 UTC | |
|
Re: Define string on current line, then match other lines with string below the line
by QM (Parson) on Oct 03, 2014 at 10:36 UTC | |
|
Re: Define string on current line, then match other lines with string below the line
by mr_mischief (Monsignor) on Oct 03, 2014 at 17:14 UTC | |
by Mashed Potato (Initiate) on Oct 05, 2014 at 14:14 UTC | |
by Athanasius (Archbishop) on Oct 05, 2014 at 16:04 UTC | |
by mr_mischief (Monsignor) on Oct 06, 2014 at 18:14 UTC |