Succinct way to print all lines up until the last line that matches a given pattern Succinct way to print all lines up until the last line that matches a given pattern shell shell

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.


Load the data into an array line by line, and throw the array away when you find a pattern match. Print out whatever is left at the end.

 while (<>) {     @x=() if /$pattern/;     push @x, $_; } print @x;

As a one-liner:

 perl -ne '@x=() if /$pattern/;push @x,$_;END{print @x}' input-file


Alternatively: tac "$file" | sed -n '/PATTERN/,$p' | tac

EDIT: If you don't have tac emulate it by defining

tac() {    cat -n | sort -nr | cut -f2}

Ugly but POSIX.