TARGET
How to delete all lines in a text file before a matching one, including this one?
Input file example:
apple
pear
banana
HI_THERE
lemon
coconut
orange
Desired output:
lemon
coconut
orange
The aim is to do it in sed to use the "-i" option (direct editing).
CLEAN SOLUTION ?
Most answers for similar problems propose something like:
sed -n '/HI_THERE/,$p' input_file
But the matched line is not deleted:
HI_THERE
lemon
coconut
orange
Then, knowing this will delete all from matched line (including it) to end of file:
sed '/HI_THERE/,$d' input_file
I tried something like this:
sed '^,/HI_THERE/d' input_file
But then sed complains:
sed: -e expression #1, char 1: unknown command: `^'
DIRTY SOLUTION
The last (dirty) solution is using pipeline:
sed -n '/HI_THERE/,$p' input_file | tail -n +2
but then, direct edit of the file doesn't work:
sed -n '/HI_THERE/,$p' input_file | tail -n +2 > input_file
cat input_file # returns nothing
and one must use a temporary file like that…
sed -n '/HI_THERE/,$p' input_file | tail -n +2 > tmp_file
mv tmp_file input_file
Best Answer
Similar to your "clean solution":
The first line in the file is line 1 - there's no special
^
address because you always know that, while$
is needed for the end because you don't (necessarily) know which line that is.This does fall over if the matching line is the first line of the file. With GNU sed you can use
0
instead of1
to deal with that. For POSIX sed and for portability (which seem to be different in this case) it's more complex (see comments below and this follow-up question).