Zu has asked for the wisdom of the Perl Monks concerning the following question:
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?
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Efficient method to replace middle lines only when no match
by AnomalousMonk (Archbishop) on Mar 19, 2014 at 02:47 UTC | |
by Zu (Initiate) on Mar 20, 2014 at 06:54 UTC | |
by AnomalousMonk (Archbishop) on Mar 20, 2014 at 15:49 UTC | |
|
Re: Efficient method to replace middle lines only when no match
by AnomalousMonk (Archbishop) on Mar 19, 2014 at 03:55 UTC | |
|
Re: Efficient method to replace middle lines only when no match
by kcott (Archbishop) on Mar 19, 2014 at 06:34 UTC | |
by Zu (Initiate) on Mar 20, 2014 at 07:21 UTC |