来自一个文件的 awk 搜索列,如果匹配来自两个文件的打印列 [英] awk search column from one file, if match print columns from both files

查看:32
本文介绍了来自一个文件的 awk 搜索列,如果匹配来自两个文件的打印列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试比较 file1 中的第 1 列和文件 2 中的第 3 列,如果它们匹配,则打印 file1 中的第一列和 file2 中的前两个列.

I'm trying to compare column 1 from file1 and column 3 from file 2, if they match then print the first column from file1 and the two first columns from file2.

以下是每个文件的示例:

here's a sample from each file:

文件1

Cre01.g000100   
Cre01.g000500  
Cre01.g000650  

文件2

chromosome_1    71569  |655|Cre01.g000500|protein_coding|CODING|PAC:26902937|1|1)
chromosome_1    93952  |765|Cre01.g000650|protein_coding|CODING|PAC:26903448|11|1)
chromosome_1    99034  |1027|Cre01.g000100 |protein_coding|CODING|PAC:26903318|9|1)

想要的输出

Cre01.g000100  chromosome_1    99034        
Cre01.g000500  chromosome_1    71569   
Cre01.g000650  chromosome_1    93952

我一直在查看一些有点相似的各种线程,但我似乎无法让它打印两个文件中的列.以下是一些相关的链接:

I've been looking at various threads that are somewhat similar, but I can't seem to get it to print the columns from both files. Here are some links that are somewhat related:

awk 比较 2 个文件,2 个字段在文件中的不同顺序,打印或合并匹配和不匹配的行

获取来自文件的模式,与另一个文件的列进行比较,打印匹配的行,使用 awk

awk 比较两个文件中的列,估算另一列的值

使用 ack 或 awk 或比 grep 更好的方式从另一个文件中获取模式?

Awk - 合并 2 个文件中的数据,如果键匹配,则打印到第 3 个文件

我觉得我应该能够根据这些线程弄清楚它,但是这两天我一直在尝试不同的代码变体,但我没有得到任何结果.这是我尝试在我的文件上使用的一些代码:

I feel like I should have been able to figure it out based on these threads, but it's been two days that I've been trying different variations of the codes and I haven't gotten anywhere. Here is some code that I've tried using on my files:

awk 'FNR==NR{a[$3]=$1;next;}{print $0 ($3 in a ? a[$3]:"NA")}' file1 file2

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

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

我知道我必须创建一个临时矩阵,其中包含 file1 的第一列(或 file2 的第三列),然后将其与另一个文件进行比较.如果匹配,则打印文件 1 中的第一列和文件 2 中的第 1 列和第 2 列.

I know i have to create a temp matrix that contains the first column of file1 (or the 3rd column of file2) then compare it to the other file. If there is a match, then print first column from file1 and column 1 and column 2 from file 2.

感谢您的帮助!

推荐答案

你可以使用这个awk:

awk -F '[| ]+' -v OFS='	' 'NR==FNR{a[$4]=$1 OFS $2; next}
       $1 in a{print $1, a[$1]}' file2 file1
Cre01.g000100   chromosome_1    99034
Cre01.g000500   chromosome_1    71569
Cre01.g000650   chromosome_1    93952

这篇关于来自一个文件的 awk 搜索列,如果匹配来自两个文件的打印列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆