regex - Perl:如何在文件中插入行?
问题描述
我正在阅读两个文件。每当第 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 中的行
- 从 line1 的行首提取整数
- 如果该整数存在于您的哈希中
- 打印 file2 中的行
推荐阅读
- ibm-midrange - 如何在 AS400 中获取用户的电子邮件 ID?
- c++ - SIMD 性能基准
- mysql - MYSQL 在命令中运行查询以更新显示 bash 错误的表数据
- r - 在 dplyr 包中找不到跨函数
- c# - 加载本地 XML 文档
- javascript - 多页表单:如何根据请求无限期地重复一页?HTML、CSS、JS
- dask - 如何在 dask 数组维度上迭代 da.linalg.inv
- python - 向现有表添加新列 - Flask Sqlalchemy
- canvas - 在垂直滚动排列多个列表框的同时水平滚动
- javascript - 制表符:如何在数据编辑/更改后触发过滤器