我不確定我是否理解你的代碼塊(「承諾」有什麼用途?什麼是&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
節。
它讀起來好像每個「祈願」字的每一邊需要20個字符,無論「$ searchword」設置爲什麼?你能澄清嗎? – Marty
此外,除「searchword found」外,它不會打印任何我們可以看到的內容 - 也就是說''write_excel'會執行某些操作,但是您沒有發佈它的內容。 – Marty
我很抱歉,祈願應該讀「樂趣」。此外,這是一個子例程,寫入excel部分在我的代碼後面。如果這有幫助,我可以發佈一切。 –