问题
Say I have a file xx.txt and it contains the data
1 I am here
2 to work in
3 Perl for writing
4 a script for
5 myself
Suppose i want to search for string script and want to display the three lines above it , what should i do ?
回答1:
You can use an array as your print buffer.
my @array;
while (<DATA>) {
push @array, $_;
shift @array if @array > 4;
print @array if /script/;
}
__DATA__
1 I am here
2 to work in
3 Perl for writing
4 a script for
5 myself
Various usage:
If you intend to use this as a stand-alone, you might consider using grep instead:
grep -B3 script xx.txt
Or perl one-liner if grep is not an option (e.g. you're on Windows):
perl -nwe 'push @a, $_; shift @a if @a > 4; print @a if /script/' xx.txt
If it is inside a script, you only need to supply your own file handle:
my @array;
open my $fh, '<', "xx.txt" or die $!
while (<$fh>) {
push @array, $_;
shift @array if @array > 4;
print @array if /script/;
}
来源:https://stackoverflow.com/questions/9329501/how-to-read-n-lines-above-the-matched-string-in-perl