比较两个文件并将第二个文件中的行写入第一个文件

时间:2014-03-24 00:05:49

标签: perl

我有两个名为test1和test2的文件。文件内容如下。

TEST1

nijin:qwe123
nijintest:qwerty
nijintest2:abcsdef
nijin2:qwehj

TEST2

nijin:qwe
nijintest2:abc

我必须更改test1中nijinnijintest2的值以匹配test2中的值,只留下所有其他值。我已经尝试了所有可能的Perl替换注释但没有任何成功。任何帮助将不胜感激。

修改

我已经尝试了许多打开的关闭文件函数来替换条目,但它们都没有提供所需的输出。我在这里尝试了一切In Perl, how do I change, delete, or insert a line in a file, or append to the beginning of a file?。但没有运气

2 个答案:

答案 0 :(得分:1)

虽然它可能仍然可以被压缩,但仍然有效:

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

die "Usage: $0 map [file ...]\n" unless scalar(@ARGV) >= 1;

my %mapping;
open my $fh, "<", $ARGV[0] or die "Failed to open $ARGV[0] for reading";
while (<$fh>)
{
    my($key, $value) = ($_ =~ m/^([^:]*):(.*)/);
    $mapping{$key} = "$value\n";
}
close $fh;

shift;

while (<>)
{
    my($key) = ($_ =~ m/^([^:]*):/);
    $_ = "$key:$mapping{$key}" if (defined $mapping{$key});
    print;
}

如果它被称为sub.pl,您可以运行:

perl sub.pl test2 test1
perl sub.pl test2 <test1
perl sub.pl test2 test1 test3 test4

对于前两次调用,输出为:

nijin:qwe
nijintest:qwerty
nijintest2:abc
nijin2:qwehj

答案 1 :(得分:0)

以下内容适用于导入任意数量的新文件。我还提供了附加新条目的代码,但没有说明您希望如何处理。

#!/usr/bin/env perl
use strict;
use warnings;
use autodie;

die "Usage: $0 dbfile [mapfiles ...]\n" if @ARGV < 2;

my $db = shift;

my %mapping = map {chomp; /([^:]*)/; $1 => $_} <>;

local @ARGV = $db;
local $^I = '.bak';
while (<>) {
    chomp;
    /([^:]*)/;
    print delete $mapping{$1} // $_, "\n";
}
#unlink "$db$^I"; # Uncomment if you want to delete backup

# Append new entries;
open my $fh, '>>', $db;
$fh->print($_, "\n") for values %mapping;