【问题标题】:Compare two files and print matching lines with some lines after match比较两个文件并在匹配后用某些行打印匹配行
【发布时间】:2017-07-07 07:27:27
【问题描述】:

我有两个文件 file1.txt 和 file2.txt。

file1.txt

DS496218    40654   42783   
DS496218    40654   42783
DS496218    40654   42783

file2.txt

###
DS496108    ena gene    99942   102567  .   -       
DS496128    ena mRNA    99942   102567  .   -       
DS496118    ena three_prime_UTR 99942   100571  
###
DS496218    ena gene    40654   42783   .   -       
DS496108    ena mRNA    99942   102567  .   -       
DS496108    ena three_prime_UTR 99942   100571      
###
DS496128    ena gene    99942   102567  .   -       
DS496133    ena mRNA    99942   102567  .   -       
DS496139    ena three_prime_UTR 99942   100571  
###

我想将 file1.txt 的第 1,2 和 3 列与 file2.txt 的第 1,4 和 5 列相匹配。如果匹配,则将匹配行与以下行打印到###,但不打印###。我在

中使用“awk”命令进行了尝试
awk -F'\t' 'NR==FNR{c[$1$2$3]++;next};c[$1$4$5] > 0' file1.txt file2.txt > out.txt. 

【问题讨论】:

  • 尝试使用 'in' 选项。即:$1$4$5 in c {在这里做事}
  • 试试awk 'NR==FNR{c[$1$2$3]++; next} $1$4$5 in c' file1.txt RS="###" file2.txt
  • edit 你的问题包括给定输入的预期输出。 @JoseRicardoBustosM。不,永远不要连接字段来创建密钥字符串,除非您有一个非常具体的目标,因为这会产生错误匹配 - 考虑 a bc -> abcab c -> abc。此外,将 RS 设置为多个字符会使脚本不必要地特定于 gawk,并且会在匹配之前和之后打印行。

标签: awk


【解决方案1】:

没有看到您的预期输出,这是一个猜测,但听起来这就是您想要的:

awk '
NR==FNR { a[$1,$2,$3]; next }
($1,$4,$5) in a { found=1 }
/^###/ { found=0 }
found
' file1 file2

【讨论】:

    猜你喜欢
    • 2017-07-30
    • 1970-01-01
    • 2015-04-08
    • 2016-07-30
    • 2020-11-24
    • 1970-01-01
    • 2012-09-05
    • 1970-01-01
    • 2018-07-12
    相关资源
    最近更新 更多