1

2 つのファイルの比較は典型的な問題であり、この問題については多くの議論があることを知っています。しかし、テキスト ファイルの操作中にはかなり別の問題があります。行数が異なる 2 つのテキスト ファイルがあります。ここで、2 つのファイルを比較して、異なる行を見つけたいと考えています。その後、両方のファイルのすべての違いにタグを付けたいと思います。たとえば、私のファイルの内容は次のとおりです。

ファイル 1.txt:

This is the first line.
This line is just appeared in File1.txt.
you can see this line in both files.
this line is also appeared in both files.
this line and,
this one are mereged in File2.txt.

ファイル 2.txt:

This is the first line.
you can see this line in both files.
this line is also appeared in both files.
this line and, this one are mereged in File2.txt.

処理後、両方のファイルを次のようにします。

ファイル 1.txt:

This is the first line.
<Diff>This line is just appeared in File1.txt.</Diff>
you can see this line in both files.
this line is also appeared in both files.
<Diff>this line and,</Diff>
<Diff>this one are merged in File2.txt.</Diff>

ファイル 2.txt:

This is the first line.
<Diff></Diff>
you can see this line in both files.
this line is also appeared in both files.
<Diff>this line and, this one are mereged in File2.txt.</Diff>
<Diff></Diff>

これどうやってするの?diffなどのツールが役立つことはわかっていますが、その結果をこの形式に変換するにはどうすればよいですか?

前もって感謝します。

4

2 に答える 2

3

Algorithm::Diff を使用できます。これは、ほぼ希望どおりの出力を生成する例です。おそらく、正確な目的の出力を得るために微調整できます。

use Algorithm::Diff;
my $diff = Algorithm::Diff->new( \@seq1, \@seq2 );

my @out1;
my @out2;

while(  $diff->Next()  ) {
    if ($diff->Same) {
        push @out1, $diff->Items(1);
        push @out2, $diff->Items(2);
    }
    elsif (not $diff->Items(2) ) {
        for ($diff->Items(1)) {
            chomp;
            push @out1, "<Diff>$_</Diff>\n";
        }
        push @out2, "<Diff></Diff>\n";
    }
    elsif (not $diff->Items(1)) {
        for ($diff->Items(2)) {
            chomp;
            push @out2, "<Diff>$_</Diff>\n";
        }
        push @out1, "<Diff></Diff>\n";
    }
    else {
        for ($diff->Items(1)) {
            chomp;
            push @out1, "<Diff>$_</Diff>\n";
        }
        for ($diff->Items(2)) {
            chomp;
            push @out2, "<Diff>$_</Diff>\n";
        }
    }
}

出力:

@out1:
This is the first line.
<Diff>This line is just appeared in File1.txt.</Diff>
you can see this line in both files.
this line is also appeared in both files.
<Diff>this line and,</Diff>
<Diff>this one are mereged in File2.txt.</Diff>


@out2:
This is the first line.
<Diff></Diff>
you can see this line in both files.
this line is also appeared in both files.
<Diff>this line and, this one are mereged in File2.txt.</Diff>
于 2012-06-17T12:06:42.677 に答える
3

diffGNU diffutils から使用している場合は、--old-line-formatおよび--new-line-formatオプションを に試すことができますdiff

diff --old-line-format "<Diff></Diff>%c'\012'" \
     --new-line-format "<Diff>%l</Diff>%c'\012'" \
     File1.txt File2.txt > NewFile1.txt

diff --old-line-format "<Diff>%l</Diff>%c'\012'" \
     --new-line-format "<Diff></Diff>%c'\012'" \
     File1.txt File2.txt > NewFile2.txt

詳細については、man ページを参照してください。「LTYPE-line-format」および「GTYPE-group-format」を検索します。

于 2012-06-17T20:16:35.827 に答える