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:
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 sed
script 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 the b
command to "branch" to it (goto). This:
sed '/^[ \t]*$/{: a;N;/#matchee/!P;D;/^[ \t]*$/b a}' file.txt
is a loop of the following:
a
← this is a no-op, just a place to goto
#matchee
, print L1
goto a
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With