2014-08-29 60 views
-5

代替我有一个文件:map.txt - 这是具有1000+线等以下格式:快速多个搜索和在Perl

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

我有具有5条百万+线input.txt另一文件;
其中包含aaa为"aaa",bbb为"bbb"格式。

我可以买到在Perl中最快速的方法来建议搜索&替换的所有发生:
"aaa""123"
"bbb""4567"

+2

使用哈希。非常简单,除非你有嵌套引号。 – TLP 2014-08-29 10:04:20

+1

另请参阅后续讨论:http://stackoverflow.com/questions/25579821/perl-not-matching-multiple-hash-keys-comes-in-a-single-line – tripleee 2014-08-30 08:15:18

回答

1

使用哈希。使用旧字符串作为键,替换字符串作为值。

#!/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; 
} 

输出到一个新文件,修改的最后一段如下:

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; 
+0

第二部分在屏幕上正确打印;但我想重定向到output.txt,对我来说工作不正常。要么获得与'input.txt'相同的'output.txt',要么获得'map.txt'中未提及的那些变量的一些额外的空替换。你能否更新代码以正确地重定向到'output.tx'? – Brijesh 2014-08-29 14:27:14

+0

@Brijesh:你是说如果你运行'map.pl> output.txt',它不起作用? – choroba 2014-08-29 14:38:37

+0

不是这样,实际上我没有试过,也不能这样做,因为这部分是一个大型Perl程序的一部分。我需要将本节的输出作为'output.txt'来进一步处理.. – Brijesh 2014-08-29 14:45:29

0

可能是这样的:

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

my %hash = (
    aaa => '123', 
    bbb => '4567', 
    cc => '89', 
) 

open FILE, '>', 'input.txt'; 
while(<FILE>) 
{ 
    if(/"([a-z]+)"/) { 
     s/"$1"/'"'.$hash{$1}.'"'/ge if($hash{$1}); 
    } 
}  
+2

''“'。$ hash { $ 1}'''''写得更好'qq(“$ hash {$ 1}”)''。但为什么要使用评估,它不是一个好主意,而且不需要:'“hash {$ 1}”' – TLP 2014-08-29 11:17:29