A line-by-line approach might actually be more efficient/maintainable, but if the file's already slurped, maybe something like this (needs Perl 5.10+ for  \K but this could be worked around):

c:\@Work\Perl\monks>perl -wMstrict -le "use 5.010; ;; my $s = qq{yada\n} . qq{field1: valueA\n} . qq{some\n} . qq{lines\n} . qq{here\n} . qq{field3: valueC\n} . qq{blah blah\n} ; print qq{[[$s]]}; ;; my $replace = qq{field2: valueB\n}; ;; $s =~ s{ ^ field1: \s valueA \n \K (?! \Q$replace\E) .*? (?= field3: \s valueC \n) } {$replace}xmsg; print qq{[[$s]]}; " [[yada field1: valueA some lines here field3: valueC blah blah ]] [[yada field1: valueA field2: valueB field3: valueC blah blah ]]

Update 1: Changed  (?! $replace) to  (?! \Q$replace\E)

Update 2: I don't know if I just missed it or it was added after I began my reply, but the code at the bottom of the OP looks a lot like my post, and in fact is better since it takes care of variable value fields as mine does not. ?!?


In reply to Re: Efficient method to replace middle lines only when no match by AnomalousMonk
in thread Efficient method to replace middle lines only when no match by Zu

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.