2016-04-26 70 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功能和<>操作一个文件的内容装载到一个变量。