我正在读取两个文件。每当第 1 列内容匹配时,我都会尝试从 file2 到 file1 插入一行。
##文件1
1 wr 5769 78670002 fqefq
3 wr 5769 78650003 hfhhg
5 wr 5769 88990001 dfdsv
##文件2
1 Step1
3 Step3
5 Step5
期望的输出:
1 wr 5769 78670002 fqefq
Step1
3 wr 5769 78650003 hfhhg
Step3
5 wr 5769 88990001 dfdsv
Step5
尝试过的代码:
my $rk="rk.log";
open(my $tt, "<$rk" ) or die "Could not open file $trk: $!";
while (<$tt>) {
if ($_ =~ /^(\d+)\s+wr\s+5769\s+(\w+)\s+\.*/gm) {
open(p1,"<$temp1") or die "Could not open file $temp1: $!";
while (my $newl = <p1>) {
my @fs1 = split " ", $newl;
if ($fs1[0] eq $1){
print "@fs1\n";
print "step $2\n";
} else {
print "@fs1\n";
}
}
}
}
close p1;
close $tt;
上面的代码没有给出所需的输出。谁能建议我更好的方法吗?
更新##FILE2
2 Step1
4 Step3
6 Step5
最佳答案
希望一些伪代码足以让您走上正轨。
- 将 file2 读入哈希(其中键是整数,值是整行)
- 打开文件1
- 一次读取 file1 一行
- 打印 file1 中的行
- 从第 1 行的行首提取整数
- 如果该整数存在于您的哈希中
- 打印 file2 中的行
关于regex - Perl:如何在文件中插入行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65561431/