$ sed -n '/^\[/h; /^\[/,/^\]/H; ${x;s/^\[\n//;p;}' file
[
eighth
]
Annotated sed
script (assumes -n
):
/^\[/h; # replace hold space with this line
/^\[/,/^\]/H; # append these lines to hold space with embedded newlines
${ # at last line of input
x; # swap in the hold space
s/^\[\n//; # delete the first "[" and the newline following it
p; # print
}
That is, whenever we find a line that starts with [
, clear the hold space by copying the line there. Then keep appending lines to the hold space until we find the corresponding line that starts with ]
.
At the end, we will have a hold space with one [
too many, so delete that (and the embedded newline after it) before printing the data.