Shell – Print nth line before the matched line, Matching line and nth line from the matched line

shellshell-scripttext processing

I want Print nth line before the matched line, Matching line and nth line from the matched line where "n" is greater than 2.

Here's an example of my data file (the line numbers below are not part of the data and just for identification), The pattern that I am searching for is "blah", in the example.txt file.

$ cat example.txt 
 1. a
 2. b
 3. c
 4. d
 5. blah
 6. e
 7. f
 8. g
 9. h
 10. blah
 11. i
 12. f
 13. g
 14. h

And I want the Output as:

 1. b
 2. blah
 3. g
 4. f
 5. blah
 6. g

Please suggest any one liner!

Best Answer

Here's a perl one-liner:

$ perl -ne '$n=3;push @lines,$_; END{for($i=0;$i<=$#lines;$i++){
  if ($lines[$i]=~/blah/){
    print $lines[$i-$n],$lines[$i],$lines[$i+$n]}}
 }' example.txt 
b
blah
g
f
blah
g

To change the number of surrounding lines, change $n=3; to $n=N where N is the desired number. To change the matched pattern, change if ($lines[$i]=~/blah/) to if ($lines[$i]=~/PATTERN/).

If the numbers are actually part of the file, you can do something like this:

$ perl -ne '$n=3;push @lines,$_; END{for($i=0;$i<=$#lines;$i++){
      if ($lines[$i]=~/blah/){
        print $lines[$i-$n],$lines[$i],$lines[$i+$n]}}
     }' example.txt | perl -pne 's/\d+/$./'
1. b
2. blah
3. g
4. f
5. blah
6. g
Related Question