print lines between two regex if string founded in lines in sed

StackOverflow https://stackoverflow.com/questions/23567727

  •  19-07-2023
  •  | 
  •  

سؤال

similar this question

i have this file

START1
1
2
END1
START2
error
1
2
END2
START3
1
2
END3

i want if error found; sed extract the whole piece and print it

for example out put is

START2
error
1
2
END2

because error found between START2 and END2

how to solve it only with sed ?!?

هل كانت مفيدة؟

المحلول

Using sed:

sed -n ':a;/START/,/END/{/END/!{$!{N;ba;}};/error/p;}' inputfile

The idea is to keep adding the lines in the pattern space between the two specified addresses. If the regex (string error in this case) is found, then print the block. -n wouldn't print anything unless explicitly specified.

For your sample input, it'd produce:

START2
error
1
2
END2

نصائح أخرى

Perl solution:

perl -ne '
   $inside = 1 if /START/;
   push @lines, $_ if $inside;
   $error = 1 if /error/ and $inside;
   if (/END/) {
       print @lines if $error;
       undef @lines;
       $inside = 0;
       $error = 0;
   }
' file
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top