【问题标题】:best way to merge every other line from two different files合并来自两个不同文件的每一行的最佳方法
【发布时间】:2015-09-12 21:43:24
【问题描述】:

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

文件 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 行与 file2 中的第 2 行相同)。我对 perl one liner 没有经验,但我认为 one liner 可以比我的脚本更快地完成这项任务。

【问题讨论】:

  • 两个文件的长度是否相同?两个文件之间的公共线是否完全相同?
  • 这两个文件的长度相同,除了我正在组合的行之外,它们的长度相同。至于没有之间的界限。我将编辑它们以代表文件。对此感到抱歉。

标签: perl concatenation lines


【解决方案1】:
#!/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
$ 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-05
    • 2012-07-17
    • 2020-01-25
    • 2021-07-30
    • 2023-03-29
    相关资源
    最近更新 更多