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:
To change the number of surrounding lines, change
$n=3;
to$n=N
whereN
is the desired number. To change the matched pattern, changeif ($lines[$i]=~/blah/)
toif ($lines[$i]=~/PATTERN/)
.If the numbers are actually part of the file, you can do something like this: