Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use sed to match between two patterns and get the next line after the second pattern?

Tags:

sed

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.

like image 712
chad512 Avatar asked Sep 05 '25 02:09

chad512


1 Answers

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:

  • How to print lines between two patterns, inclusive or exclusive
  • Printing with sed or awk a line following a matching pattern
like image 87
Sundeep Avatar answered Sep 07 '25 20:09

Sundeep