How can I emulate 'grep -B' functionality in Perl?

后端 未结 3 1050
梦谈多话
梦谈多话 2021-01-20 10:45

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

3条回答
  •  既然无缘
    2021-01-20 11:45

    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!

提交回复
热议问题