【问题标题】:compare first column in two files and print the first column same which is in first file比较两个文件中的第一列并打印与第一个文件中相同的第一列
【发布时间】:2020-11-26 15:51:02
【问题描述】:

file1.txt

YGR192C
YLR044C
YLR110C
YKL152C
YOR382W

file2.txt

YLR044C PDC1
YGR192C TDH3
YLR110C CCW12
YKL152C GPM1
YOR382W FIT2

预期输出:与 file1.txt 中的第 1 列顺序相同,与 file2.txt 中第 2 列的匹配值

YGR192C TDH3
YLR044C PDC1
YLR110C CCW12
YKL152C GPM1
YOR382W FIT2

任何帮助将不胜感激

【问题讨论】:

  • 欢迎来到 SO,请在您的问题中添加您的努力,这是对 SO 的强烈鼓励。
  • 您也可以使用 SO 的搜索功能,在这里您也可以找到此类问题。

标签: linux awk


【解决方案1】:
$ awk 'NR==FNR{map[$1]=$0; next} $1 in map{print map[$1]}' file2 file1
YGR192C TDH3
YLR044C PDC1
YLR110C CCW12
YKL152C GPM1
YOR382W FIT2

【讨论】:

  • 非常感谢@Ed Mortan....脚本非常适合我。
  • 欢迎您,请参阅stackoverflow.com/help/someone-answers 了解下一步操作。
  • 我不知道那是什么意思。我发布的答案解决了您提出的问题,因此您应该接受该答案并提出一个新问题(如果有的话)。
【解决方案2】:

试试这个 -

awk 'FNR==NR{a[$1]++;next} ($1 in a) {print $1}' file2.txt file1.txt
YGR192C
YLR044C
YLR110C
YKL152C
YOR382W

没有 awk -

grep -f <(cut -d" " -f1 file2.txt) file1.txt
YGR192C
YLR044C
YLR110C
YKL152C
YOR382W

【讨论】:

    【解决方案3】:

    你可以这样做:

    awk 'FNR==NR{seen[$1]; next}  # read each element of file2 first col
         $1 in seen               # if there, print
    ' file2 file1
    

    由于预期的输出改变了,你可以这样做:

    awk 'FNR==NR{seen[$1]=$0; next}  # read each line of file2 indexed by first col
         $1 in seen { print seen[$1] }              # if there, print the line
    ' file2 file1
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-07
      • 2017-09-18
      • 1970-01-01
      • 2020-08-20
      • 1970-01-01
      相关资源
      最近更新 更多