Perl从一个文件中记录变量,在另一个文件中搜索并替换它
这将是我的第一个问题。我想通过使用Perl实现以下目标。Perl从一个文件中记录变量,在另一个文件中搜索并替换它,perl,file,search,replace,Perl,File,Search,Replace,这将是我的第一个问题。我想通过使用Perl实现以下目标。 代码应在文件2中搜索文件1中提到的参数,并将文件2中“:”之后的值替换为文件1中的值。代码应就地替换,且不得更改/排序文件中参数的顺序 文件1: config1: abc config2: bcd config3: efg 文件2: config1: cba config2: sdf config3: eer config4: 343 config5: sds config6: dfd 输出-->文件2应如下所示: config1:
代码应在文件2中搜索文件1中提到的参数,并将文件2中“:”之后的值替换为文件1中的值。代码应就地替换,且不得更改/排序文件中参数的顺序 文件1:
config1: abc
config2: bcd
config3: efg
文件2:
config1: cba
config2: sdf
config3: eer
config4: 343
config5: sds
config6: dfd
输出-->文件2应如下所示:
config1: abc
config2: bcd
config3: efg
config4: 343
config5: sds
config6: dfd
- 使用
读取文件1File::Slurp
- 对于每一行,使用
或正则表达式将键和值分开,并将此键值对附加到split
哈希中%文件
- 对于每一行,使用
- 要真正替换到位,请在Perl的命令行中使用
参数;(您可以尝试使用-pi
,但可能更难)Tie::Hash
- 您可以通过使用
将file2读入散列%file2,使用File::Slurp
的循环键将%hash2
值覆盖在%file1
值之上,来模拟这一点,在正确的循环中构造键valye字符串后,再次使用%hash2
将生成的File::Slurp
写入file2%hash2
使用strict;
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
使用警告;
#存储文件1中的参数
我的妻子;
打开(my$FILE1,“file2_adjusted.txt”)或死亡$!;
在arr2处打印$FILE2W;
关闭$FILE2W
这听起来像是家庭作业(替换到位和保持参数顺序是任意约束,在一个小的KVP配置文件中与现实生活没有任何关联)。您能说明您尝试了什么以及遇到了什么困难吗?StackOverflow不是“为我做工作/家庭作业”网站。感谢回复…我已经用正则表达式创建了一个工作代码行…循环等…不是家庭作业:P…只是这个网站的新成员。