合并两个不同文件中每隔一行的最佳方法

best way to merge every other line from two different files

我正在尝试将每隔一行合并到两个文件中。我试图改编我的一个旧脚本,通过使用哈希链接 。解释这一点的最好方法是通过展示一个例子,不能很好地表达它。如果您对我的任务还有其他疑问,请在下方评论,我会澄清。

文件 1:

>blue
it is a 2006 toyota
>red
it is a 1990
>black
it is a mongoose
>blue
it is a 2010

文件 2:

>car
it is a 2006 toyota
>jeep
it is a 1990
>bike
it is a mongoose
>jeep
it is a 2010

预期输出:

>blue|car
it is a 2006 toyota
>red|jeep
it is a 1990
>black|bike
it is a mongoose
>blue|jeep
it is a 2010

我在使用旧脚本时遇到的问题是它会删除任何重复的元素,而我不想重复出现。因为在我的实际文件中,两个文件的第二行是相同的(文件 1 中的第 2 行与文件 2 中的第 2 行相同)。我对 perl one liners 没有经验,但我认为 one liner 可以比我的脚本更快地完成这项任务。

#!/usr/bin/perl --
use warnings;
use strict;

open my $in1, "<", 'file1.txt' or die $!;
open my $in2, "<", 'file2.txt' or die $!;

while (<$in1>) {

    chomp;
    print;

    my $file2line = <$in2>;
    print "|", substr($file2line,1);

    my $whatitis  = <$in1> or last;
    <$in2> || undef; # throw file2's line away

    print $whatitis;
}

close $in1;
close $in2;

输出:

$ more file1.txt 
>blue
it is a 2006 toyota
>red
it is a 1990
>black
it is a mongoose
>blue
it is a 2010
$ more file2.txt 
>car
it is a 2006 toyota
>jeep
it is a 1990
>bike
it is a mongoose
>jeep
it is a 2010
$ perl script2.pl
>blue|car
it is a 2006 toyota
>red|jeep
it is a 1990
>black|bike
it is a mongoose
>blue|jeep
it is a 2010
$