我正在尝试编写一个Perl脚本,该脚本将执行以下操作:比较来自不同源目录的两个具有相同名称的文件,这意味着:
diff source_dir_1/file_1 source_dir_2/files_2
对于file_2中的每个更改的行(与file_1相比),它将在第三个文件source_dir_3 / file_3中找到来自file_1(在file_2中已更改)的行,并将此行替换为file_2中的行。
例如,用于:
文件_1:
我的名字叫Shahar
Hello World,
很高兴认识你
文件_2
我的名字叫Shahar
Goodbye World
很高兴认识
file_3:
这条线可以与
世界不同的Hello World
Nice相遇
结果file_3将是:
file_3_after_script:
这条线可以不同,
再见世界,
尼斯见面
我在编写它时遇到了问题,因为有时file_1中的一行会替换为file_2中的几行,
您对我应该如何解决此问题有任何建议吗?
您的目标尚不清楚。始终将您在任何关于SO的问题中尝试过的代码都包括在内。
但是,当然可以同时打开3个文件并对它们执行逻辑。
以下是我对您的目标的最佳解释。它循环遍历每个文件的行,如果file1和2不同,则从file2打印该行,否则打印file3。
use strict;
use warnings;
use autodie;
my $file1 = '...';
my $file2 = '...';
my $file3 = '...';
#open my $fh1, '<', $file1;
#open my $fh2, '<', $file2;
#open my $fh3, '<', $file3;
# Open to strings temporarily to make script self-contained:
open my $fh1, '<', \ "My name is Shahar\nHello World\nNice to meet\n";
open my $fh2, '<', \ "My name is Shahar\nGoodbye World\nNice to meet\n";
open my $fh3, '<', \ "This line can be different\nHello World\nNice to meet\n";
while (! grep eof $_, $fh1, $fh2, $fh3) {
my $line1 = <$fh1>;
my $line2 = <$fh2>;
my $line3 = <$fh3>;
print $line1 ne $line2 ? "file2: $line2" : "file3: $line3";
}
print "file3: $_" while (<$fh3>); # Print rest of file (if any)
输出:
file3: This line can be different
file2: Goodbye World
file3: Nice to meet
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句