2012-07-19 152 views
3

我正在對兩行文本文件ref.txt(參考)和log.txt進行比較。但是任何一個文件中可能會有任意數量的空白行,我想忽略它們;我怎麼能做到這一點?比較兩個文件時,如何跳過(忽略)空白行?

ref.txt

one 

two 


three 



end 

log.txt的

one 
two 
three 
end 

會有輸出沒有不正確的日誌行,在log.txtref.txt匹配等字樣。

我喜歡什麼僞代碼來完成:

while (traversing both files at same time) { 
    if ($l is blank line || $r is blank line) { 
     if ($l is blank line) 
      skip to next non-blank line 
     if ($r is blank line) 
      skip to next non-blank line 
    } 
    #continue with line by line comparison... 
} 

我當前的代碼:

use strict; 
use warnings; 

my $logPath = ${ARGV [0]}; 
my $refLogPath = ${ARGV [1]} my $r; #ref log line 
my $l;         #log line 

open INLOG, $logPath or die $!; 
open INREF, $refLogPath or die $!; 

while (defined($l = <INLOG>) and defined($r = <INREF>)) { 
    #code for skipping blank lines? 
    if ($l ne $r) { 
     print $l, "\n";    #Output incorrect line in log file 
     $boolRef = 0;     #false==0 
    } 
} 

回答

2

您可以通過比較這正則表達式跳過空白行:

next if $line =~ /^\s*$/ 

這將匹配任何可能構成空行的空格或換行符。

+0

對我來說,寫下'除非$ line =〜/ \ S /'似乎更容易理解(至少對我來說)。 – 2012-07-20 10:34:46

+0

@DaveCross我想你的版本可以確保在線讀取有一些東西。總是有更多的方法來完成它INT Perl! – squiguy 2012-07-20 13:05:38

+0

是的。在處理一個太多的「空行」實際上包含空格和/或製表符的文件之後,我切換到了我的方法。 – 2012-07-20 13:11:34

0

您可以循環找到的每一行,每一時間:

while(1) { 
    while(defined($l = <INLOG>) and $l eq "") {} 
    while(defined($r = <INREF>) and $r eq "") {} 

    if(!defined($l) or !defined($r)) { 
     break; 
    } 

    if($l ne $r) { 
     print $l, "\n"; 
     $boolRef = 0; 
    } 
} 
0
man diff 

diff -B ref.txt log.txt 
+0

問題是如何在Perl中完成它。 – Annjawn 2012-07-19 16:48:10

0
# line skipping code 
while (defined($l=<INLOG>) && $l =~ /^$/) {} # no-op loop exits with $l that has length 

while (defined($r=<INREF>) && $r =~ /^$/) {} # no-op loop exits with $r that has length 
7

如果你是一個Linux平臺上,使用:

diff -B ref.txt log.txt 

-B選項導致的變化只需插入或刪除空白行即可忽略

2

這種方式似乎對我來說是最「類似perl」的。沒有花哨的循環或任何東西,只是啜泣的文件和grep出空行。

use warnings; 

$f1 = "path/file/1"; 
$f2 = "path/file/2"; 

open(IN1, "<$f1") or die "Cannot open file: $f1 ($!)\n"; 
open(IN2, "<$f2") or die "Cannot open file: $f2 ($!)\n"; 

chomp(@lines1 = <IN1>); # slurp the files 
chomp(@lines2 = <IN2>); 

@l1 = grep(!/^\s*$/,@lines1); # get the files without empty lines 
@l2 = grep(!/^\s*$/,@lines2); 

# something like this to print the non-matching lines 
for $i (0 .. $#l1) { 
    print "[$f1 $i]: $l1[$i]\n[$f2 $i]: $l2[$i]\n" if($l1[$i] ne $l2[$i]); 
} 
+0

也許重寫這些greps爲'@ l1 = grep(/ \ S /,@ lines1)'等 – 2012-07-20 10:35:32

+0

如何從@ l1和@ l2中檢索單行? – jerryh91 2012-07-20 15:47:34

+0

這並不完美,因爲一條不匹配的行會使所有位於下面的行不匹配。我以爲我會分享這個作爲perl的文件啜泣/ grepping能力的探索。如果可以的話,肯定只是使用'diff -B'。 – kevlar1818 2012-07-20 16:21:23

相關問題