Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
888 views
in Technique[技术] by (71.8m points)

Fast multiple search and replace in Perl

I have a file: map.txt - which is having 1000+ lines like below format:

aaa { 123 };
bbb { 4567 };
cc { 89 };

I have another file input.txt having 5 Million+ lines;
which contains aaa as "aaa", bbb as "bbb" format.

Can I get a suggestion for a fastest method in perl to search & replace all occurrence of:
"aaa" with "123"
"bbb" with "4567" so on.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Use a hash. Use the old strings as keys, replacement strings as values.

#!/usr/bin/perl
use warnings;
use strict;

my %map;
open my $MAP, '<', 'map.txt' or die $!;
while (<$MAP>) {
    my ($pattern, $replacement) = /(.*) { (.*) };/;
    $map{$pattern} = $replacement;
}

open my $IN, '<', 'input.txt' or die $!;
while (<$IN>) {
    s/"(.*)"/"$map{$1}"/g;
    print;
}

To output to a new file, change the last paragraph as follows:

open my $IN,  '<', 'input.txt' or die $!;
open my $OUT, '>', 'output.txt' or die $!;
while (<$IN>) {
        s/"(.*?)"/exists $map{$1} ? qq{"$map{$1}"} : qq{"$1"}/ge;
    print {$OUT} $_;
}
close $OUT;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...