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 ?


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.


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

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).

  • yes I would like to delete the lines after the pattern matching . Can you provide easy understanding of sed command tutorial ? Commented Sep 26, 2013 at 10:57
  • Could you please explain the terms used in 'sed -ne '/pattern/{p;n;n;n;n;d;}' -e p' comamnd Commented Sep 26, 2013 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 https://stackoverflow.com/a/15400287/1729501

Not the answer you're looking for? Browse other questions tagged .