I have the following code that will remove lines with the pattern banana and 2 lines after it:
sed '/banana/I,+2 d' file
So far, so good! But I need it to remove 2 lines before banana, but I can't get it with a minus sign or whatever (similar to what grep -v -B2 banana file should do but doesn't):
teresaejunior@localhost ~ > LC_ALL=C sed '-2,/banana/I d' file
sed: invalid option -- '2'
teresaejunior@localhost ~ > LC_ALL=C sed '/banana/I,-2 d' file
sed: -e expression #1, char 16: unexpected `,'
teresaejunior@localhost ~ > LC_ALL=C sed '/banana/I,2- d' file
sed: -e expression #1, char 17: unknown command: `-'
awk '{l[m=NR]=$0}/banana/{for(i=NR-2;i<=NR;i++)delete l[i]}END{for(i=1;i<=m;i++)if(i in l)print l[i]}'. This is not efficient, so this is just a hint, not a solution. – manatwork Jan 24 '12 at 16:38tac file | sed ... | tac. :P – angus Jan 24 '12 at 16:54