문제

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