我不确定我是否理解你的代码块(“承诺”有什么目的?是什么&write_excel
?),但我可以自己回答你的问题。
首先,这个 grep 命令可以接受吗?它更快更干净:
grep -i -C2 --color "fun" "file"
该-C NUM
标志告诉grep
提供围绕每个模式匹配的 NUM 行上下文。显然,--color
它是可选的,但它可以帮助您在很长的行中找到匹配项。
否则,这里有一点 perl:
#!/usr/bin/perl
my $searchword = "fun";
my $inputfile = "file";
my $blue = "\e[1;34m"; # change output color to blue
my $green = "\e[1;32m"; # change output color to green
my $nocolor = "\e[0;0m"; # reset output to no color
my $prev1 = my $prev2 = my $result = "";
open (INPUT, '<', $inputfile) or die "fatal error reading the file \n";
while(<INPUT>) {
if (/$searchword/i) {
$result .= $prev2 . $prev1 . $_; # pick up last two lines
$prev2 = $prev1 = ""; # prevent reusing last two lines
for (1..2) { # for two more non-matching lines
while (<INPUT>) { # parse them to ensure they don't match
$result .= $_; # pick up this line
last unless /$searchword/i; # reset counting if it matched
}
}
} else {
$prev2 = $prev1; # save last line as $prev2
$prev1 = $_; # save current line as $prev1
}
}
close $inputfile;
exit 1 unless $result; # return with failure if without matches
$result =~ # add colors (okay to remove this line)
s/([^\e]{0,20})($searchword)([^\e]{0,20})/$blue$1$green$2$blue$3$nocolor/g;
print "$result"; # print the result
print "\n" unless $result =~ /\n\Z/m; # add newline if there wasn't already one
错误:这假设之前的两行和之后的两行实际上是 20+ 个字符。如果你需要解决这个问题,它会出现在else
节中。