Re: Replacing multi-line expression



Ben Bacarisse wrote:

sed -e :a -e '$!N;s/^string1\nstring2$/string3\
string4/;ta' -e 'P;D'

However, neither of these work for me:

Script started on Thu 27 May 2010 20:20:56 BST
$ cat eg
string1
string2
xxxx
string1
string2
xxxx
$ sed -e :a -e '$!N;s/^string1\nstring2$/string3\
string4/;ta' -e 'P;D' <eg
string3
string4
xxxx
string1
string2
xxxx

Right, my bad. These should work:

$ sed '$!N;s/^string1\nstring2$/string3\
string4/' -e 'P;D' eg
string3
string4
xxxx
string3
string4
xxxx
$ sed '$!N;s/^string1\nstring2$/string3\
string4/;t' -e 'P;D' eg

Basically the jump can be removed, or it can be to the end of the script. If
the replacement does not overlap with the searched text, they are virtually
equivalent.

I may have got some detail wrong. I'd investigate further except I find
sed to be the closest thing to write-only code that I come across these
days. (It's old age I am sure -- I used to be fine with TECO.)

I think:

sed -e '/^string1$/N' -e 's/^string1\nstring2$/string3\nstring4/;t' -e
'P;D'

This also works but I like it less (just personal taste).

fixes the issue you pointed out, but it uses a default jump target. Is
there such a things as bad sed style? :-)

Some people on this list say that using sed for anything else than simple
substitutions on the same line is bad, so we better stop it here :-)
(although in most cases I agree with that because simpler alternatives
exist)
.