I need to remove a blank line prior to a match.
So given the file:
random text
more random text
#matchee
I need to match the pattern /#matchee/, then delete the blank line before it.
Here’s what I’ve tried — no success:
sed '/^[ \t]*$/{N;/#matchee.*$/{D;}}' file.txt
My logic:
- If blank line; append next line to pattern space yielding /blank line\n…etc/
- If pattern space contains /#matchee/, Delete up to newline yielding /#matchee/
Basically /matchee/ is a constant that must be maintained and I need to remove an extra
blank line from each record in a file of records delimited by /#matchee/.
This produces no effect whatever. I am RTFM-ing and D is supposed to delete pattern
space up to the newline. Since N appends a newline plus next line — this should produce the desired results ….alas ….no and no again. Is this because the match contains essentially nothing ( blankline )?
Your approach will work if there are an odd number of blank lines, but it will fail if there are an even number. Your
sedscript is a loop of the following.#matchee, discard L1 from the pattern spaceYou’ll notice that L2 is always printed, even if it’s blank and followed by a line that contains
#matchee. It’s protected by the fact that it immediately follows an odd number of blank lines.Edited to add: To fix the above-described problem, you can add an inner loop by using the
:command to create a label and thebcommand to “branch” to it (goto). This:is a loop of the following:
a← this is a no-op, just a place togoto#matchee, print L1goto a