【问题标题】:How to merge diff result between two files into a third file?如何将两个文件之间的差异结果合并到第三个文件中?
【发布时间】:2014-08-18 06:07:25
【问题描述】:

我正在尝试编写一个 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 中的行。

例如,对于:

file_1:

我的名字是沙哈尔
你好世界
很高兴认识

file_2

我的名字是沙哈尔
再见世界
很高兴认识

file_3:

这条线可以不同
你好世界
很高兴认识

生成的 file_3 将是:

file_3_after_script:

这条线可以不同
再见世界
很高兴认识

我在编写它时遇到问题,因为有时 file_1 中的一行会被 file_2 中的几行替换,

你对我应该如何解决这个问题有什么建议吗?

【问题讨论】:

  • 您的描述不清楚。 file_1 和 file_2 中的第一行相同,但您仍将其替换为 line_3 中的行。
  • 您可能会发现Algorithm::Diff 很有用。
  • 听起来像是three way merge 问题。试试google,看看问题是否已经用其他工具解决了。

标签: regex perl


【解决方案1】:

你的目标不明确。在任何关于 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

【讨论】:

    【解决方案2】:

    试试这个

    open (file1,'file_1');
    open (file2,'file_2');
    open (file3,'file_3');
    @f1= <file1>;
    @f2 = <file2>;
    @f3 = <file3>;
    print "$f3[0]\n$f2[1]\n$f1[2]\n";
    

    这也给出了你尝试的输出。

    【讨论】:

    • 谢谢你我使用了之前的建议,它很有帮助
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-13
    • 2011-12-07
    • 2023-04-04
    • 1970-01-01
    相关资源
    最近更新 更多