Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

This question already has an answer here:

I want to remove a particular number of lines after the given pattern is matched.

Can anyone please tell me how that can be done using the sed command ?

share|improve this question

marked as duplicate by terdon, Anthon, slm, manatwork, jasonwryan Sep 26 '13 at 18:20

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

2 Answers 2

sed -ne '/pattern/{n;n;n;n;d;}' -e p

Would delete the line matching the pattern and 4 lines after that.

If you don't want to delete the line matching the pattern itself:

sed -ne '/pattern/{p;n;n;n;n;d;}' -e p

Explanation: if the current line matches the pattern, [p]rint it, then get the [n]ext one, and [n]ext and [n]ext, and [n]ext and [d]iscard it. Because of the [d]iscard, the [p]rint command is not run in that case. It is run for every other line. -n disables automatic printing (which would print almost everything) and thus implies the use of -e p, which makes sure the resulting lines are printed.

Example:

$ seq 8 | sed -ne '/2/{p;n;n;n;n;d;}' -e p
1
2
7
8

To be able to specify the number of lines as a number, it would be easier with awk:

awk 'n>0 {n--;next}; /pattern/{n=4}; 1'

(note that in all those solutions, the pattern is not looked for in the lines that are being skipped).

share|improve this answer
    
yes I would like to delete the lines after the pattern matching . Can you provide easy understanding of sed command tutorial ? –  user2720323 Sep 26 '13 at 10:57
    
Could you please explain the terms used in 'sed -ne '/pattern/{p;n;n;n;n;d;}' -e p' comamnd –  user2720323 Sep 26 '13 at 11:09

Two step, assuming bash. Assuming 2 lines to be removed after the lines containing "pattern". Note: The line which contains pattern is NOT removed, but 2 lines after that are removed.

To remove N lines, change A2 -> AN in grep arguments

grep -n -A2 pattern inputFile | grep -Ev pattern | sed 's/^\([0-9]*\)-.*/\1/g' > linesToRemove

while read p; do sed -i "${p}d" inputFile; done < linesToRemove

If you also want to delete the line containing pattern, change grep command to

grep -n -A2 pattern inputFile | sed 's/^\([0-9]*\)[-:].*/\1/g' > linesToRemove

Explanation: First command finds out line numbers of lines to be deleted. Second command deletes these lines one after another. Use http://explainshell.com/ to learn more or just man grep

If your sed does not have -i option, read http://stackoverflow.com/a/15400287/1729501

share|improve this answer

Not the answer you're looking for? Browse other questions tagged or ask your own question.