in reply to Contextual find and replace large config file
"The data files often don't have any official format." -> Then it's hopeless and you should give up. :)
Or
The following program works for your test case #2 (and some things you might have missed).
You should only have to change the "configuration section" to alter different things,
after, of course, fixing it to actually read and write files.
If it doesn't work on one of your large files, please show a small failed test case,
and we'll see what we can do :)
#!/usr/bin/perl # https://perlmonks.org/?node_id=1227916 use strict; use warnings; ##################### configuration section my $section = 'ObjectType1'; my %changes = ( Param1 => 0, Param2 => 'SomeOtherText', Param3 => 'Foo +bar'); ##################### end configuration section my $allkeys = join '|', keys %changes; my $pattern = qr/\b($allkeys)\b/; local $/ = "\n}\n"; while( <DATA> ) { if( /\b$section\b/ ) { my @context; print $& while @context && $context[-1] eq $section && /\G(\h*$pattern = ).*\n/ +gc ? "$1$changes{$2}\n" =~ /.*/s : @context && /\G\h*\}\n/gc ? pop @context : /\G\h*([\w ]+)\n\h*\{\n/gc ? push @context, $1 : /\G.*\n/gc; } else { print; } } __DATA__ ObjectType1 { Param1 = 8 NestedObject { Param1 = 3 Param2 = SomeText } Param2 = SomeText } ObjectType2 { Foo { Param1 = StaySame ObjectType1 { Param3 = ReplaceThis } } } ObjectType1 { ... }
Outputs:
ObjectType1 { Param1 = 0 NestedObject { Param1 = 3 Param2 = SomeText } Param2 = SomeOtherText } ObjectType2 { Foo { Param1 = StaySame ObjectType1 { Param3 = Foobar } } } ObjectType1 { ... }
I'm also curious about benchmark times vs any other solution (since I'm not going to generate a 500000 line test file).
|
---|