Current solutions except schrodigerscatcuriosity's print the file contents even when there's no match. schrodigerscatcuriosity's involves using tac
and so requires reading the whole input before looking for matches.
Here's another way to do it with just sed
and printing only when there's a match:
sed -n '1h;1!H;/foo/{g;p;q}'
1h
-- copy pattern space to hold space when on the first line1!H
-- append pattern space to hold space when not on the first line/foo/{...}
-- on matching/foo/
,g
-- copy hold space to pattern spacep
-- print pattern spaceq
-- quit