[英]Find a match using regex - perl
我有一個TCPDUMP文件,其中包含USER和PASS單詞的許多用法,我需要計算出一個正則表達式以查找所有單詞,然后打印出每個單詞的數量。 (或任何其他方式;盡管如此,正則表達式是我的首選)。 我認為我的分歧似乎行不通。 不知道我在這里怎么做錯了,所以有什么想法嗎? 提前致謝!
這是輸入文件的示例(注意:這只是2006行的文件的第一行。格式相同,但是數字,符號和字母在每一行中都發生變化)
22:28:28.374595 IP 98.114.205.102.1821 > 192.150.11.111.445: Flags [S], seq 147554406, win 64240, options [mss 1460,nop,nop,sackOK], length 0E...<.@.q...br.f...o.... ...\.bfP....Y..echo open 0.0.0.0 8884 > USER 1 1 >>
碼:
#!/usr/bin/perl -w
use strict;
use warnings;
use diagnostics;
#opens txt file: read mode
open MYFILE, '<', 'source_file.txt' or die $!;
#opens output txt file: write mode
open OUT, '>', 'Summary_Report.txt' or die $!;
#open output txt file: write mode
#used to store header 'split' info
open OUTFILE, '>', 'Header.txt' or die $!;
my $start_time = undef;
my $end_time;
my $linenum = 0;
my $user;
my $pass;
while (<MYFILE>) {
chomp;
$linenum++;
#print ": $_\n"; ###if I need to see the lines (check)###
#separate pieces of information from TCPDUMP into list
my @header = split (' ',$_);
print OUTFILE "$linenum: @header\n\n";
if (/^22:28/ && !defined($start_time)) {
$start_time = $header[0];
#print "$start_time\n"; ###used as a check###
}
if ($_ = /22:28/) {
$end_time = $header[0];
}
if ($_ =~ m/USER/i) {
$user = $header[10];
}
}
print OUT "Total # of times phrases were used:\n\n
USER (variations thereof) = $user\n\n
PASS (variations thereof) = $pass\n\n\n";
我不太了解perl,但是我知道regex ...,您可以使用此表達式來匹配以22.28開頭的任何行,該行還包含USER / PASS:
(?<=22\.28)USER|PASS
我不清楚您的需求,如果您進一步指定,我可能會幫助您。
my @lines = (<MYFILE>);
my @matches = grep { $_ =~ /(PASS|USER)/i } @lines;
應該管用?
帶行號:
my @lines = (<MYFILE>);
my %results;
map {
if ($lines[$_] =~ /(pass|user)/i) {
$results{$_} = $lines[$_];
}
} 0..$#lines;
%results將具有鍵作為行號,值是line。 Grep更快,因為它是遞歸的,這將是O(n2)iirc。
現在..
map {
#separate pieces of information from TCPDUMP into list
my @header = split (' ',$results[$_]);
print OUTFILE "$_: @header\n\n";
if (/^22:28/ && !defined($start_time)) {
$start_time = $header[0];
#print "$start_time\n"; ###used as a check###
}
if ($results[$_] = /22:28/) {
$end_time = $header[0];
}
if ($results[$_] =~ m/USER/i) {
$user = $header[10];
}
} keys %results;
這是一個USER / PASS計數選項:
use strict;
use warnings;
my %user_pass;
while (<DATA>) {
$user_pass{$1}++ while /(\bUSER\b|\bPASS\b)/g;
}
print "$_ => $user_pass{$_}\n" for keys %user_pass;
__DATA__
USER USER PASS PASS
PASS
USER
USER
PASS PASS
輸出:
PASS => 5
USER => 4
希望這可以幫助!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.