【问题标题】:Command line to consider common values in only in specific column仅在特定列中考虑公共值的命令行
【发布时间】:2014-02-18 06:54:17
【问题描述】:

我正在寻找一个简单的命令行来帮助我完成以下任务。

我有两个文件,我想打印它们在 Col2 中具有共同值的行。

例如 File1 类似于下面的 3 列制表符分隔示例

文件1

cat big 24
cat small   13
cat red 63

文件2

dog big 34
chicken plays   39
fish    red 294

想要的输出

big
red

我尝试过使用commsyntax 的命令:comm /path/to/file1/ /path/to/file2 但是,它不会输出任何东西,因为 Col1 和 Col3 中的值很少有共同点。 有没有人对如何解决这个问题提出建议,也许awk 是一个更好的解决方案?

【问题讨论】:

    标签: linux awk terminal command-line-arguments comm


    【解决方案1】:

    如果您阅读 comm 的手册页,您会发现它适用于 sorted 文件。但是awk很灵活,你可以控制你想要的:

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

    【讨论】:

      【解决方案2】:

      您可以使用pasteawk 一次性完成:

      paste file1 file2 | awk '$2 == $5 { print $2 }'
      

      输出:

      big
      red
      

      【讨论】:

      • 这是有风险的..想想file2中的行是red then big
      • @Kent:当然,这假设file1 中的n 行应该与file2 中的n 行进行比较。我就是这样理解这个问题的。
      猜你喜欢
      • 1970-01-01
      • 2021-10-12
      • 1970-01-01
      • 2019-01-17
      • 1970-01-01
      • 1970-01-01
      • 2022-01-27
      • 2022-07-21
      • 2013-04-20
      相关资源
      最近更新 更多