質問

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