我如何在Perl中模拟'grep -B'功能? [英] How can I emulate 'grep -B' functionality in Perl?

查看:116
本文介绍了我如何在Perl中模拟'grep -B'功能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在寻找一种解决方案,它可以让我搜索一个数组的行,并且如果字符串匹配成功,将该行和前两行压入数组中。看起来这很容易使用 grep 命令完成。但是,我无法得到这个工作。这是我有:

  sub ipsearch {
my $ ip = $ _ [0];
我的@IPVSCONFIG = grep(/ \W + virtual \s $ ip \s /,@RAWDATA);
}

是否可以将-B 2语法添加到grep命令?我已经尝试了几种形式的语法,但是我无法完成它的工作:

  @IPVSCONFIG = grep -B 2 \W + virtual \s $ ip \s /,@RAWDATA); 

请让我知道这是否可能,以及正确的语法应该是什么。如果您有任何其他建议,请告诉我们。



感谢您的帮助!

解决方案



获取匹配的索引:

  my @matchedIndices = grep {$ RAWDATA [$ _] =〜/ \W + virtual \s $ ip \s /} 2 .. $#RAWDATA; 

获取指数:

  my @wantedIndices = map {($ _- 2 .. $ _)} @matchedIndices; 

然后取一个数组slice:

  my @IPVSCONFIG = @RAWDATA [@wantedIndices]; 

完全采用Schwartzian变换:

  my @IPVCONFIG = map {@RAWDATA [$ _- 2 .. $ _]} 
grep {$ RAWDATA [$ _] =〜/ \ W + virtual \s $ ip \s /}
2 .. $#RAWDATA;

绝对比传统的命令行 grep -B 2更繁忙


I have been searching for a solution that allows me to search the lines of an array, and if a string match is made, push that line and the 2 previous lines into an array. It seems this would be easily done using the grep command. However, I cannot get this to work. This is what I have:

sub ipsearch {
    my $ip = $_[0];
    my @IPVSCONFIG =  grep (/\W+virtual\s$ip\s/, @RAWDATA);
}

Is it possible to add the "-B 2" syntax to the grep command? I've tried several forms of this syntax but I cannot get it to work:

@IPVSCONFIG =  grep -B 2 (/\W+virtual\s$ip\s/, @RAWDATA);

Please let me know if this is even possible, and what the correct syntax should be. If you have any other suggestions, please let me know.

Thanks for the help!

解决方案

The trick is to identify the lines where the match occurs, then identify the relevant indices around:

Get the matched indices:

my @matchedIndices = grep { $RAWDATA[$_] =~ /\W+virtual\s$ip\s/ } 2 .. $#RAWDATA;

Get the indices around:

my @wantedIndices  = map { ( $_-2 .. $_ ) } @matchedIndices;

And take an array slice:

my @IPVSCONFIG = @RAWDATA[ @wantedIndices ];

Putting it altogether in a Schwartzian transform:

my @IPVCONFIG = map  { @RAWDATA[$_-2..$_] }
                grep { $RAWDATA[$_] =~ /\W+virtual\s$ip\s/ }
                2 .. $#RAWDATA ;

Definitely a much busier solution than the traditional command-line grep -B 2!

这篇关于我如何在Perl中模拟'grep -B'功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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