Remove lines based on pattern by keeping first n lines

view story

http://unix.stackexchange.com – I need to remove lines from a text file based on pattern but I need to keep the first n lines of that pattern. Input % 1 % 2 % 3 % 4 % 5 text1 text2 text3 output %1 %2 text1 text2 text3 I used sed /^%/d file but it deletes all the lines starting with %, sed 3,/^%/d doesn't help either. I need to keep first n lines of the pattern and delete the rest (HowTos)