Succinct way to print all lines up until the last line that matches a given pattern
Here's a sed-only solution. To print every line in $file
starting with the last line that matches $pattern
:
sed -e "H;/${pattern}/h" -e '$g;$!d' $file
Note that like your examples, this only works properly if the file contains the pattern. Otherwise, it outputs the entire file.
Here's a breakdown of what it does, with sed commands in brackets:
- [H] Append every line to sed's "hold space" but do not echo it to stdout [d].
- When we encounter the pattern, [h] throw away the hold space and start over with the matching line.
- When we get to the end of the file, copy the hold space to the pattern space [g] so it will echo to stdout.
Also note that it's likely to get slow with very large files, since any single-pass solution will need to keep a bunch of lines in memory.