如何在perl中读取匹配字符串上方的n行? [英] How to read n lines above the matched string in perl?

查看:60
本文介绍了如何在perl中读取匹配字符串上方的n行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个文件 xx.txt 并且它包含数据

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 ?

推荐答案

您可以使用数组作为打印缓冲区.

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

各种用法:

如果你打算单独使用它,你可以考虑使用 grep 代替:

If you intend to use this as a stand-alone, you might consider using grep instead:

grep -B3 script xx.txt

或者 perl one-liner 如果 grep 不是一个选项(例如你在 Windows 上):

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/;
}

这篇关于如何在perl中读取匹配字符串上方的n行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆