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)
.



Relevant Pages

  • inserting a newline character in a bash (or sh) shell
    ... I've been looking for a way to do this in a fancy grep script I'm developing ... However the newline insertion doesn't work and I get something like: ...
    (comp.unix.shell)
  • Re: dynamic variable names or using a variable as anothers name
    ... stringD which are all associated with string1 and stringA. ... That sounds like a hash where each value is a hash where each value is ... the value is an array containing stringB,stringC,stringD. ... to access it in various places during a single run of the script, ...
    (comp.lang.ruby)
  • Re: pushing value to $t->src
    ... After quite a bit of poking around in the script, I actually got it to work, well 99.9% anyway. ... $string1 = abcdef; ... $string4 = stuvwx; ...
    (perl.beginners)
  • Replacing multi-line expression
    ... without much success so far. ... cat input.dump | sed -e '{ ... I then tried with awk: ... string1 was present in the file. ...
    (comp.unix.shell)
  • Re: Replacing multi-line expression
    ... without much success so far. ... cat input.dump | sed -e '{ ... But this one simply gives an empty output file. ... string1 was present in the file. ...
    (comp.unix.shell)