As long as you can guarantee that the substring to match will not extend over more than two lines, you could use a two-line sliding buffer that you apply the substitution to, but then split again before outputting (so you won't get everything twice):

#!/usr/bin/perl use strict; use warnings; my $prev = ""; my $done = 0; while (<DATA>) { # sliding two-line buffer $_ = $prev.$_; # get rid of middle newline, so it doesn't interfere with match s/\n//; s/<\?string\?>/<xxx>/g; # split buf # first part will be output, second part kept # for joining with next input line ($_, $prev) = unpack "a".length($prev)."a*", $_; print "$_\n" if 2 .. $done; # corner case: have last line be printed as well if (eof and !$done++) { $_ = ""; redo } } __DATA__ hello there this is a bad <?string?> that we need to take away. Here is another bad <?st ring?> that needs to go too.

Output:

hello there this is a bad <xxx> that we need to take away. Here is another bad <xxx > that needs to go too.

As you can see, line breaks may be occur anywhere in the middle of the substitution. If that's a problem, you'd have to modify the logic of splitting the sliding buffer (which can get tricky...).

(There may be corner cases I've overlooked, but you get idea...)


In reply to Re: Search and replace over line break by almut
in thread Search and replace over line break by Anonymous Monk

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.