Based on the awesome answer found here, I'm trying to use some of these commands inside a sed
scriptfile that will be called using sed -f
. The file has multiple sed
commands and it's been working without a problem. Now I need to add these two lines to the end of the file:
/^$/{N;s/^$\nbegin of this/begin/g}
/^$/{N;s/^$\nend of this/end/g}
which basically searches for an empty line (^$
) followed by the next with the phrase begin of this
or end of this
, and proceeds to delete the empty line and replace the next line just with begin
or end
.
Each command run independently works without any problems but when put inside a scriptfile, hell breaks lose. Some of my previous commands stop working (i.e. s/\\ \\ //g
which just deletes the string \ \
). More importantly, only the first, of the previous two multiline commands, is executed, why? Am I missing some command-line switch for sed
? Is it possible to have multiple multiline commands in the same scriptfile?
As extra "points", I would love to replace those two regex lines with a capturing group, i.e. /^$/{N;s/^$\n(begin|end) of this/\1/g}
but that also doesn't work, not even running it directly on the command line.
I really hope this has a relatively easy/doable solution since I rather not use perl
or awk
, but if this is a limitation of sed
itself or it's extremely complicated to accomplish, I will (very much reluctantly) use the alternatives.
Here's a very basic sample text:
some text
begin of this
some more text
end of this
A sentence
Another sentence
Which should end up looking like this:
some text
begin
some more text
end
A sentence
Another sentence
sed -r -f
. I'll add a sample text to the question – Felipe May 01 '20 at 18:16sed -r '/^$/{$!N;s:^\n(begin|end) of this$:\1:}' file.txt
. – seshoumara May 02 '20 at 16:59/^$/
doesn't "look for" empty lines. If the pattern space is empty at that point in the script, it matches. – Kusalananda May 02 '20 at 18:37