I'm not entirely sure that sed is the best tool for this job. The problem is that sed is so line-oriented, and you need to maintain state (at least at some level) to do this.
A quick stab at how I might do this (probably in Perl): track through the file line by line; every time I see PATTERN, note the line number (just one variable for this $last_seen); then rewind to the top of the file and only print back out up to the line number that I was left with.
The general problem is that whatever tool you use has no obvious way of knowing whether the
next line is another occurrence of PATTERN or EOF.
An example, not very fancy:
Code:
#!/usr/bin/env perl
use strict;
use warnings;
open my $fh, '<', 'file.txt'
or die "Can't open 'file.txt' for reading: $!";
my $last_seen;
while (<$fh>) {
$last_seen = $. if $_ =~ /PATTERN/;
print $., "\n";
}
open my $out, '>', 'new_file.txt'
or die "Can't open 'new_file.txt' for writing: $!";
seek($fh, 0, 0);
$. = 0;
while (<$fh>) {
print $out $_;
print $., "\n";
last if $. == $last_seen;
}