This might work for you (GNU sed):
sed '/apple/,$!b;//!H;//{x;//p;x;h};${x;P};d' file
Print as usual any lines that are not from the first appearance of apple
to the end of the file. For lines within the above range, append lines that do not contain the word apple
to the hold space (HS). Lines that do contain the word apple
, first swap to the HS and print any line there if the word apple
is there, then replace the HS with the line containing apple
. Delete all lines other than the last line. At the endof file print the first line of the HS and delete the remaining lines.
If slurping a large file is not a problem use:
sed -rz 's/(.*apple[^\n]*).*/\1\n/' file
This uses greed to capture all lines before and including the word apple
.