【问题标题】:Perl Noting a variable from one file, searching it in another and replacing it [closed]Perl注意到一个文件中的变量,在另一个文件中搜索并替换它[关闭]
【发布时间】:2013-10-11 10:34:41
【问题描述】:

这是我的第一个问题。我想通过使用 Perl 来实现以下目标。
代码应在 File2 中搜索 File1 中提到的参数,并将 File 2 中“:”后面的值替换为 File1 中的值。代码应就地替换,不要更改/排序文件中参数的顺序。

文件 1:

config1: abc
config2: bcd
config3: efg

文件 2:

config1: cba
config2: sdf
config3: eer
config4: 343
config5: sds
config6: dfd

输出 --> File2 应该是这样的:

config1: abc
config2: bcd
config3: efg
config4: 343
config5: sds
config6: dfd

【问题讨论】:

  • 这听起来像是作业(就地替换并保持参数顺序是任意约束,在小型 KVP 配置文件中与现实生活的相关性为零)。您能否展示您尝试过的内容以及遇到的困难? StackOverflow 不是“为我做我的工作/家庭作业”的网站。

标签: perl file search replace


【解决方案1】:
use strict;
use warnings;

#store params from file1
my (%params);

open(my $FILE1, "< file1.txt") or die $!;
my @arr = <$FILE1>;
foreach(@arr){ 
   #extract key-value pairs \s* = any number of spaces, .* = anything
   #\w+ = any sequence of letters (at least one)
   my ($key, $value) = ($_ =~ /(\w+)\s*:\s*(.*)/);
   $params{$key}=$value; 
}
close $FILE1;

open(my $FILE2, "< file2.txt") or die $!;
my @arr2 = <$FILE2>;
foreach(@arr2){
   my ($key, $value) = ($_ =~ /(\w+)\s*:\s*(.*)/);
   #if the found key did exist in params, then replace the found value, with 
   #the value from file 1 (this may be dangerous if value contains regexp chars, 
   #consider using e.g. \Q...\E
   if (exists $params{$key}) {
       #replace the row in @arr2 inline using direct ref $_
       $_ =~ s/$value/$params{$key}/;
   }
}
close $FILE2
#replace / output the result /here to a different file, not to destroy
open(my $FILE2W, "> file2_adjusted.txt") or die $!;
print $FILE2W @arr2;
close $FILE2W

【讨论】:

    【解决方案2】:
    • 使用File::Slurp读取文件1
      • 对于每一行,使用split 或正则表达式将键与值分开,并将此键值对附加到%file 哈希中。
    • 要真正就地替换,请在 Perl 的命令行中使用-pi 参数; (您可以尝试使用Tie::Hash,但可能会更难)。
    • 您可以通过使用File::Slurp 将file2 读取到散列%file2 中来模拟此操作,使用%hash2 键的循环将%file1 值覆盖在%hash2 值之上,然后写入结果@987654330在正确的循环中构造 key-valye 字符串后,再次使用 File::Slurp @ 回到文件 2。

    如果您在特定步骤中遇到困难,请说明您的操作以及问题所在,以便我们帮助解决问题

    【讨论】:

    • 感谢您的回复......我已经使用正则表达式创建了一个工作代码线......循环等......不是家庭作业:P......只是这个网站的新手。
    猜你喜欢
    • 2013-01-06
    • 1970-01-01
    • 2014-02-16
    • 2018-11-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多