Delete lines before and after a match in bash (with sed or awk)?

Viewed 20001

I'm trying to delete two lines either side of a pattern match from a file full of transactions. Ie. find the match then delete two lines before it, then delete two lines after it and then delete the match. The write this back to the original file.

So the input data is

D28/10/2011
T-3.48
PINITIAL BALANCE
M
^

and my pattern is

sed -i '/PINITIAL BALANCE/,+2d' test.txt

However this is only deleting two lines after the pattern match and then deleting the pattern match. I can't work out any logical way to delete all 5 lines of data from the original file using sed.

6 Answers

A more simple and easy to understand solution might be:

awk '/PINITIAL BALANCE/ {print NR-2 "," NR+2 "d"}' input_filename \
    | sed -f - input_filename > output_filename

awk is used to make a sed-script that deletes the lines in question and the result is written on the output_filename.

This uses two processes which might be less efficient than the other answers.

Related