2016-04-26 65 views
0

這是我的腳本,用於檢查文件中是否存在版權。使用grep的Perl多行模式匹配

use strict; 
use warnings; 
use List::Util 'first'; 

my $filename="sample.txt"; # this file name will be passed-in to the script. 
my @fileContent=`cat $filename`; 
my $copyrightFound = first { /copyright .* Shakespeare/i } @fileContent; 
if (!$copyrightFound) { 
    print "\nERROR: Copyright missing\n"; 
    exit; 
} 
#copyright Found 
print @fileContent; 
if (grep /Copyright (c) \d+ by Bill Shakespeare\nAll rights reserved./,@fileContent) { 
    print "\nCopyright is good\n"; 
} else { 
    print "\nCopyright needs to be fixed\n"; 
} 

打印:

$ perl copyrightCheck.pl 
Copyright (c) 2010 by Bill Shakespeare 
All rights reserved. 


Copyright needs to be fixed 

但版權是好的,有沒有更好的辦法來檢查呢?或者我的grep命令有什麼問題?也可以在同一行或下一行出現All rights reserved.,我可以用\n*查看一樣嗎?

回答

1

問題是您將文件加載到文件行的數組中,因此Copyright (c) 2010 by Bill ShakespeareAll rights reserved.以單獨的數組元素結尾。然後嘗試在此數組的元素上匹配您的多行版權字符串,該字符串失敗。

要解決此問題,您可以嘗試將文件加載到標量中,並在該標量上使用正則表達式匹配。您還需要逃避,你想匹配任何括號:

my $fileContent = `cat $filename`; 
... 
if ($fileContent =~ /Copyright \(c\) \d+ by Bill Shakespeare\nAll rights reserved./) 
{ 
    ... 
} 

我也建議你使用Perl的open功能和<>操作一個文件的內容裝載到一個變量。