How to read n lines above the matched string in perl?

删除回忆录丶 提交于 2019-12-23 14:23:13

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!