【问题标题】:grep to output to include unmatched entries toogrep 输出也包括不匹配的条目
【发布时间】:2017-11-12 07:28:55
【问题描述】:

我正在尝试根据文件 2 中的匹配项映射文件 1 中的条目。我试过了 (grep -Ff file1 file2)、join 等,但它只输出匹配的条目。例如,

File1:
Cat 
Dog
Fish
Horse

File2: (tab delimited)
Cat 'Meow Meow'
Dog Bark
Horse 'Gallop gallop'

“喵喵”是一个词。列分隔符只有 '\t'。我期望的输出是,

Output file:
Cat Meow Meow
Dog Bark
Fish
Horse Gallop gallop

怎么做?

提前致谢,

AP

【问题讨论】:

    标签: unix awk command-line grep


    【解决方案1】:

    join 命令的好案例:

    join -j1 -o1.1,2.2 -t $'\t' -a1 <(sort File1) <(sort File2)
    

    输出:

    Cat     Meow Meow
    Dog     Bark
    Fish    
    Horse    Gallop gallop
    

    • -o FORMAT - 在构造输出行时遵守FORMAT

    • -a FILENUM - 还从文件 FILENUM 打印不可配对的行,其中 FILENUM 是 1 或 2

    【讨论】:

    • 好一个!我不知道你是如何推断出这个人的输出:-o FORMAT obey FORMAT while constructing output line 虽然:)
    • @Aif,来自man joinFORMAT is one or more comma or blank separated specifications, each being 'FILENUM.FIELD' or '0'.
    • @RomanPerkhrest。它有效,但问题是,它需要空间作为分隔符。即如果第二列有“喵喵”。在输出中它写了一个对应于 cat 的喵!
    • @Arun,你没有提到你的File2 可以有超过 2 列。那是另一种情况。在最简单的情况下,您可以使用 -o1.1,2.2,2.3 扩展您的输出
    • @RomanPerekhrest,如果我不清楚,对不起。但它不超过两列,而是一个插入空格的单词。这就是我放“喵喵”的原因。唯一的列分隔符是 '\t'
    【解决方案2】:

    awk:

    awk 'FNR==NR{a[$1]=$2;next} {print $1, a[$1]}' file2 file1
    

    【讨论】:

      【解决方案3】:

      有史以来最丑的答案,使用 Perl(你当时没有得到任何答案):

      $ perl -e '%actions = (); open my $fh ,"<", $ARGV[0] ; while (<$fh>) { chomp ; $actions{$_} = ""; } close $fh; open $fh, "<", $ARGV[1] ; while (<$fh>) { chomp; ($animal, $action) = split /\s+/; $actions{$animal} = $action; } foreach (keys %actions) { print "$_ $actions{$_}\n"; } ; ' file1 file2
      Horse Gallop
      Fish 
      Dog Bark
      Cat Meow
      

      更新:限制拆分。

      $ perl -e '%actions = (); open my $fh ,"<", $ARGV[0] ; while (<$fh>) { chomp ; $actions{$_} = ""; } close $fh; open $fh, "<", $ARGV[1] ; while (<$fh>) { chomp; ($animal, $action) = split (/\s+/, $_, 2); $actions{$animal} = $action; } foreach (keys %actions) { print "$_ $actions{$_}\n"; } ; ' file1 file2
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-09-19
        • 2011-04-23
        • 2014-03-13
        • 2012-06-04
        • 1970-01-01
        相关资源
        最近更新 更多