Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

detect two consecutive lines matching a pattern with sed

Tags:

sed

I am looking for two consecutive lines matching a certain pattern, say containing word 'pat' using sed and have noticed that I am able to detect it sometimes with this command:

sed -n 'N; /.*pat.*\n.*pat.*/p'

but this command fails if the line numbers for the duplicates are not of the same parity and I assume it's because we're searching lines 1+2, 3+4, 5+6 etc.. if this is the case, what would be the correct way to do this?

like image 835
Palace Chan Avatar asked Dec 15 '22 00:12

Palace Chan


2 Answers

Why does it need to be sed? May I suggest awk?

awk '{/pat/?f++:f=0} f==2' file

If pat is found, increment f with 1
If pat is not found, reset f to 0
If f==2 print the line.

like image 191
Jotne Avatar answered Jan 30 '23 15:01

Jotne


This might work for you (GNU sed):

sed '$!N;/pattern.*\n.*pattern/p;D' file

This keeps 2 lines in the pattern space and prints both of them out if the regexp matches.

like image 29
potong Avatar answered Jan 30 '23 16:01

potong