Maybe something like:
sed 'H;/#$/!d;s/^/\
/;x;/\n%/!d;s/.//;x;s/.*//;x'
Since you want both the prompt before the error and after the error, that one includes both except for prompts that would otherwise appear both as the prompt after one error and the one before the next error to match your sample output.
It's a lot simpler if we include both prompts regardless of whether errors follow each other or not:
sed 'H;/#$/!d;x;/\n%/!d'
If you wanted only the prompt before the error, that would also be a lot simpler:
sed '/#$/!{H;d;}
x;/\n%/!d'
Probably the best way to explain those is translate to a more verbose language like perl
. In sed
, the hold space is like a static variable that is initialised with an empty line, and the pattern space a variable which sed
assigns in turn to every line of input. Something like:
$hold_space = "\n";
LINE: while ($pattern_space = <>) {
<sed commands go here>
print $pattern_space; # unless -n option is passed
}
The H
command translates to:
$hold_space .= $pattern_space;
The d
command translates to:
next LINE;
That is stop executing the commands, discard the pattern space and start fresh with the next line of input.
x
swaps pattern and hold space:
($pattern_space, $hold_space) = ($hold_space, $pattern_space);
So that last sed
command translates to:
$hold_space = "\n";
LINE: while ($pattern_space = <>) {
if (! ($pattern_space =~ /#$/)) { # anything other than a prompt
$hold_space .= $pattern_space;
next LINE;
}
($pattern_space, $hold_space) = ($hold_space, $pattern_space);
if (! ($pattern_space =~ /\n%/)) {
next LINE;
}
print $pattern_space;
}
Which can be re-written in a more legible fashion as:
LINE: while ($pattern_space = <>) {
if ($pattern_space =~ /#$/)) {
if ($hold_space =~ /\n%/)) {
print $hold_space;
}
$hold_space = $pattern_space;
} else {
$hold_space .= $pattern_space;
}
}
Rename $pattern_space
to $line
and $hold_space
to $current_block
and it becomes even more legible.
%
between lines with # and # even if it is the last line.all i have to include the lines with # and # and should have all the lines between them if it has got a % at the begining