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:
Get the indices around:
And take an array slice:
Putting it altogether in a Schwartzian transform:
Definitely a much busier solution than the traditional command-line
grep -B 2!