in reply to Re^2: Multiline Regex replacement in Multiline file
in thread Multiline Regex replacement in Multiline file
Hello again, akamboj84,
But I wanted to avoid the below "for" loop and instead do multi regex replacement.
...as my regex file is a long one and also i need to process a lot of files, so its kind of time/cpu consuming. I want to get rid of "for" loop...
— Re^3: Multiline Regex replacement in Multiline file
There may be some clever way to do this using Perl’s extended regular expression patterns, but if so I haven’t found it. But deployment of the for loop can likely be made much more efficient. At present, the regexen are being applied to the whole input file; but if you can read in a paragraph at a time, this will save a lot of processing, as there will then be no need for the regex engine to re-search those parts of the input string that have already been matched and replaced:
#! perl use strict; use warnings; my @regexen = ( q{\s+user\s"[^"]+"\s+password\s"[^"]+"\s+hash2\s+access(\s+console +){2}} . q{(\s+new-password-at-login)?} . q{(\s+member\s"(default|engineer|networktest)"){2}(\s+exit){0,2}}, q{\s+user\s"[^"]+"\s+password\s"[^"]+"\s+hash2\s+access(\s+console +){2}} . q{(\s+new-password-at-login)?} . q{(\s+member\s"(default|READ-ONLY)"){2}(\s+exit){0,2}}, q{\s+user\s"[^"]+"\s+password\s"[^"]+"\s+hash2\s+access} . q{(\s+(console|snmp|li)){3}\s+console(\s+new-password-at-login)?} +. q{(\s+member\s"(default|LI|li-prof1)"){2}(\s+exit){0,2}}, ); my $n = 1; my %dic = map { qr{$_} => 'REPLACE' . $n++ } @regexen; my $text; { local $/ = ''; # Paragraph mode while (my $para = <DATA>) { for my $matchkey (keys %dic) { last if $para =~ s%$matchkey%$dic{$matchkey}%g; } $text .= $para; } } print $text; __DATA__ user "testuser1" password "08Cl3V.leJKU/GskqArA0Yp4MFo" hash2 access console console new-password-at-login member "default" member "engineer" This paragraph doesn't match any of the regexen. user "v-test" password "VCp0GjSBK/KiWW.PgkQp7swXVMZ" hash2 access console console new-password-at-login member "default" member "READ-ONLY"
Output:
13:43 >perl 1011c_SoPW.pl REPLACE1 This paragraph doesn't match any of the regexen. REPLACE2 13:43 >
Hope that helps,
| Athanasius <°(((>< contra mundum | Iustus alius egestas vitae, eros Piratica, |
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^4: Multiline Regex replacement in Multiline file
by akamboj84 (Novice) on Sep 17, 2014 at 03:22 UTC | |
by choroba (Cardinal) on Sep 17, 2014 at 11:47 UTC |