I'm familiar with using sed to grab lines between two patterns. For example:
$ cat file
A
PATTERN1
B
PATTERN2
C
$ sed -n '/PATTERN1/,/PATTERN2/p' file
PATTERN1
B
PATTERN2
What I'd like to do, however, is generate this output:
PATTERN1
B
PATTERN2
C
I've come across the {n;p} syntax (example), but I can't seem to shoehorn this into the type of pattern matching I'm doing in this example problem.
You can use N
(syntax here is based on GNU sed
)
$ sed -n '/PATTERN1/,/PATTERN2/{/PATTERN2/N; p}' ip.txt
PATTERN1
B
PATTERN2
C
Using awk
$ awk '/PATTERN1/{f=1} f || (c && c--); /PATTERN2/{f=0; c=1}' ip.txt
PATTERN1
B
PATTERN2
C
which you can generalize using:
awk -v n=2 '/PATTERN1/{f=1} f || (c && c--); /PATTERN2/{f=0; c=n}'
Further Reading:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With