Frage

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 ?!?

War es hilfreich?

Lösung

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

Andere Tipps

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
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top