Perl脚本:从包含多个文件的文件夹中搜索字符串

Perl脚本:从包含多个文件的文件夹中搜索字符串,perl,Perl,我有一个包含多个.txt文件的文件夹。我想检查这些文本文件中的几个字符串,并以out.txt的形式输出,在定位字符串的上方和下方各有5行。使用grep更容易: grep -A 5 -B 5 'searchstring' *.txt > a.out 使用Perl:-) 如果您坚持使用perl oneliner perl -n -e 'if (/searchStringHere/) {print "\n\n\n\n\n$_\n\n\n\n\n"}' *.txt 更新 我突然想到你可能是w

我有一个包含多个.txt文件的文件夹。我想检查这些文本文件中的几个字符串,并以out.txt的形式输出,在定位字符串的上方和下方各有5行。

使用grep更容易:

grep -A 5 -B 5 'searchstring' *.txt > a.out
使用Perl:-)


如果您坚持使用perl oneliner

perl -n -e 'if (/searchStringHere/) {print "\n\n\n\n\n$_\n\n\n\n\n"}' *.txt
<如果GRIP解决方案适用于你,我认为它更优雅……/P> 更新

我突然想到你可能是windows用户,所以你没有grep

这段代码没有经过测试,因为我没有在这台机器上安装perl,但它应该可以工作: !#yourperl/perl

$flag, $l1, $l2, $l3, $l4, $l5, $l6;
$cnt = 5;
$file = shift;
open("$file") || die "can't open $file\n";
while (<>) {
 $l1 = $l2; # starting with reserving the lines for back print
 $l2 = $l3;
 $l4 = $l5;
 $l5 = $l6;
 $l6 = $_;
 if (/your string here/) {
   $cnt = 5;
   print ($l1$l2$l3$l4$l5$l6);# print line + 5 prev lines
   next
 }
 if ($cnt >0) { # print the next 5 lines
    print $l6;
    $cnt--;
 } 
}
$flag、$l1、$l2、$l3、$l4、$l5、$l6;
$cnt=5;
$file=shift;
打开(“$file”)| |死亡“无法打开$file\n”;
而(){
$l1=$l2;#从保留回印行开始
$l2=$l3;
$l4=$l5;
$l5=$l6;
$l6=$\;
如果(/your string here/){
$cnt=5;
打印($l1$l2$l3$l4$l5$l6);#打印行+5上一行
下一个
}
如果($cnt>0){#打印接下来的5行
打印$l6;
$cnt--;
} 
}

将grep与
-c5
选项一起使用perl:欢迎使用SO。在这里,以为例。如果有以下问题,则很难回答:1)没有代码,2)没有输入数据,3)没有预期结果。可能的重复请注意,如果您打算一次又一次地查找,您只需要一组\n\n\n\n-另一组将由下一个搜索结果生成。如果你把它放在原处,在你的搜索列表中间,每两个结果之间会有10行。当我理解这个问题时,OP需要搜索关键字周围的上下文。不是空行。哦,所以我误解了他的意思。在这种情况下,grep-C做得很好
$flag, $l1, $l2, $l3, $l4, $l5, $l6;
$cnt = 5;
$file = shift;
open("$file") || die "can't open $file\n";
while (<>) {
 $l1 = $l2; # starting with reserving the lines for back print
 $l2 = $l3;
 $l4 = $l5;
 $l5 = $l6;
 $l6 = $_;
 if (/your string here/) {
   $cnt = 5;
   print ($l1$l2$l3$l4$l5$l6);# print line + 5 prev lines
   next
 }
 if ($cnt >0) { # print the next 5 lines
    print $l6;
    $cnt--;
 } 
}