2013-11-05 27 views
0

非常感謝您的幫助。如果可以的話,我幾乎沒有開始嘗試學習PERL。我是白天的網絡工程師,已經找到了PERL腳本的用途,或者至少我認爲它會很好。我閱讀了儘可能多的帖子,試圖讓這個工作成功;在開始使用更復雜的正則表達式和其他各種各樣的東西之前,我應該回頭看看這些書。如何使用PERL提取另一個文件中的單詞之間的文本?

基本上我想要做的是從文本文件中拉出一段信息,並將其寫入另一個文件。以下是防火牆日誌;而對我來說唯一重要的信息後,IP地址和端口「內/」和IP地址和端口後的「外部/」

May 24 10:21:53 10.110.9.18 v3306 %FWSM-4-106100: access-list inside permitted tcp inside/10.110.27.5(53264) -> outside/172.23.240.2(1984) hit-cnt 1 (1-second interval) [0xee13216c, 0x0] 

May 24 10:21:53 10.110.9.18 v3306 %FWSM-4-106100: access-list inside permitted tcp inside/10.110.27.5(53265) -> outside/10.110.2.5(1984) hit-cnt 1 (1-second interval) [0xee13216c, 0x0] 

我基本上要輸出到最後看起來象下面這樣:

10.110.27.5(53264) -> 172.23.240.2(1984) 

這將是很好,如果有一種方法來刪除重複以及。

回答

3
perl -nE'@r= /(?:inside|outside)\/(\S+)/g and say join" -> ", @r' file 

沒有重複:

perl -nE'@r= /(?:inside|outside)\/(\S+)/g and !$s{"@r"}++ and say join" -> ", @r' file 

perl -nE' 
    @r= /(?:inside|outside)\/(\S+)/g; 
    if (@r and !$s{"@r"}++) { say join" -> ", @r } 
' file 
+0

這是非常棒的輝煌!很多從中學習...但初學者會很容易混淆! – jkshah

+1

@jkshah tnx;現在又有一個功能相同的例子 –

1

我將假定兩者insideoutside是在同一行上。你應該能夠通過這樣的循環掃描文件,找到匹配:

open my $fh, "<", $logfile or die "can't open $logfile for reading\n"; 

my %seen; # used for filtering dupes. 

while (<$fh>) 
{ 
    my $line = $_; 

    if ($line =~ /inside\/([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+\([0-9]+\)).*outside\/([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+\([0-9]+\))/) 
    { 
     my $hit = "$1 -> $2"; 
     print $hit, "\n" if (++$seen{$hit} == 1); 
    } 
} 
close $fh; 

我認爲這應該工作。

上面的正則表達式完全有可能是過度的。下面的代碼有一個更輕鬆一點:

open my $fh, "<", $logfile or die "can't open $logfile for reading\n"; 

my %seen; # used for filtering dupes. 

while (<$fh>) 
{ 
    my $line = $_; 

    if ($line =~ /(inside.*outside[^)]*\))/) 
    { 
     my $hit = $1; 
     $hit =~ s/(inside|outside)\///g; # remove 'inside/' and 'outside/' from string. 
     print $hit, "\n" if (++$seen{$hit} == 1); 
    } 
} 
close $fh; 
相關問題