【问题标题】:Compare two files and write the lines from second file to first file比较两个文件并将第二个文件的行写入第一个文件
【发布时间】:2014-05-01 04:31:46
【问题描述】:

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

测试1

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

测试2

nijin:qwe
nijintest2:abc

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

编辑

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

【问题讨论】:

  • 你试过的脚本在哪里?你听说过comm吗?
  • @squiguy:我没听说过comm。你有参考吗?
  • @Borodin Here 是。但是在进一步阅读之后,看起来它在这种情况下不起作用。
  • 我尝试了许多打开关闭文件功能来替换条目,但它们都没有提供所需的输出。我在这里尝试了所有stackoverflow.com/questions/4388304/…。但没有运气
  • @user183393:感谢您的努力,但您应该编辑自己的问题以提供更多信息。请不要添加cmets

标签: perl


【解决方案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

【讨论】:

    【解决方案2】:

    以下内容应该适用于导入任意数量的新文件。我还包含了用于附加新条目的代码,您没有指定要如何处理。

    #!/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;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-06
      • 1970-01-01
      • 2021-01-08
      • 1970-01-01
      相关资源
      最近更新 更多