I have a file whose contents have been slurped into a string. I'm trying to find an efficient solution that will replace content between two matching lines with different content, but only if there isn't a matching line in between.

So if the relevant portion of a proper file looked like this:

field1: valueA field2: valueB field3: valueC

then I don't want to make changes. But if it looked like this:

field1: valueA some lines here field3: valueC

then I want to correct it to look like the output of the first example.

The field names are fixed but the values could be anything. The regex below works, but when field2 exists it's quite slow. Likely due to the combination of greedy .* and negative look-ahead.

# this is quick my $no_field2 = "field1: valueA\nsome\nlines\nhere\nfield3: valueC\n"; $no_field2 .= "........................................\n" x 1000; $no_field2 =~ s/(field1:.*?$)\n(?!^field2:)(.*$)\n(^field3:) /$1\nfield2: valueB\n$3 /msx; # this is slow my $has_field2 = "field1: valueA\nfield2: valueB\nfield3: valueC\n"; $has_field2 .= "........................................\n" x 1000; $has_field2 =~ s/(field1:.*?$)\n(?!^field2:)(.*$)\n(^field3:) /$1\nfield2: valueB\n$3 /msx;

What is the most efficient, least code solution?


In reply to 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.