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.
For such a task, I would probably reach for a more advanced tool like Perl:
save this code into a file
grep.sed
and run a command like this:
You can use it so either:
This might work for you (GNU sed):
an awk one-liner may do the job:
test:
add some explanation
sed will do it:
It works next way:
to prevent appearence of pattern on the first string you should modify the script:
However it fails in case you have another
PINITIAL BALANCE
in string which are going to be deleted. However other solutions fails too =)