0

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 ?

jasonwryan
  • 73,126
user2720323
  • 3,589

2 Answers2

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

peterph
  • 30,838
0

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

user13107
  • 5,335