[comp.unix.questions] matching and replacing across line breaks

lang@PRC.Unisys.COM (Francois-Michel Lang) (12/14/89)

Can anyone provide a solution to this problem,
preferably using sed or awk or some such utility:

I want to operate on a file in such a way that every occurrence of
"foo" at the end of one line followed by "bar" at the beginning of the
next line is replaced by "quux".  I have a way to do this using sed
that works *most* of the time, but there are certain cases in which
it fails.

Specifically, on input

---
a
s
d
xxxfoo
barfoo
baryyy
q
w
e
foo
bar
t
y
last foo line
---

I want to produce

---
a
s
d
xxxquuxquuxyyy
q
w
e
quux
t
y
last foo line
---

The sed script I have (see below) won't handle
multiple consecutive occurrences of "foo\nbar",
and it also has a nasty habit of discarding the very last
input line if it happens to contain a "foo".

/foo/   {
                N
                s/foo\nbar/quux/
        }
----------------------------------------------------------------------------
Francois-Michel Lang
Paoli Research Center, Unisys         lang@prc.unisys.com      (215) 648-7256
Dept of Comp & Info Science, U of PA  lang@linc.cis.upenn.edu  (215) 898-9511

gwyn@smoke.BRL.MIL (Doug Gwyn) (12/15/89)

In article <12329@burdvax.PRC.Unisys.COM> lang@PRC.Unisys.COM (Francois-Michel Lang) writes:
>Can anyone provide a solution to this problem,
>preferably using sed or awk or some such utility:

>I want to operate on a file in such a way that every occurrence of
>"foo" at the end of one line followed by "bar" at the beginning of the
>next line is replaced by "quux".  I have a way to do this using sed
>that works *most* of the time, but there are certain cases in which
>it fails.

Since I personally feel every UNIX site should have "sam" on hand,
here's my solution:

sam -d file_to_be_edited <<!
,x/foo\nbar/c/quux/
w
q
!

You can also do this easily with TECO, but I'm more reluctant to
recommend that you take the trouble to acquire TECO.

Both "sam" and TECO are available from the UNIX System ToolChest.
I also distribute a merged version "sam" with support for DMD, MTG,
SunTools, and X bitmap front ends to sites that have valid "sam"
licensing.  (I don't know how much of that is available in the
current ToolChest version.)