文件1.txt
id No
gi|371443199|gb|JH556661.1| 7907290
gi|371443198|gb|JH556662.1| 7573913
gi|371443197|gb|JH556663.1| 7384412
gi|371440577|gb|JH559283.1| 6931777
文件2.txt
id P R S
gi|367088741|gb|AGAJ01056324.1| 5 5 0
gi|371443198|gb|JH556662.1| 2 2 0
gi|367090281|gb|AGAJ01054784.1| 4 4 0
gi|371440577|gb|JH559283.1| 21 19 2
输出.txt
id P R S NO
gi|371443198|gb|JH556662.1| 2 2 0 7573913
gi|371440577|gb|JH559283.1| 21 19 2 6931777
File1.txt 有两列,File2.txt 有四列。我想加入两个具有唯一 id 的文件(array[1] 应该在两个文件(file1.txt 和 file2.txt)中匹配,并仅给出匹配的 id 输出(请参阅 output.txt)。
我努力了join -v <(sort file1.txt) <(sort file2.txt)
。请求有关 awk 或 join 命令的任何帮助。
答案1
join
效果很好:
$ join <(sort File1.txt) <(sort File2.txt) | column -t | tac
id No P R S
gi|371443198|gb|JH556662.1| 7573913 2 2 0
gi|371440577|gb|JH559283.1| 6931777 21 19 2
附注输出列顺序重要吗?
如果是,请使用:
$ join <(sort 1) <(sort 2) | tac | awk '{print $1,$3,$4,$5,$2}' | column -t
id P R S No
gi|371443198|gb|JH556662.1| 2 2 0 7573913
gi|371440577|gb|JH559283.1| 21 19 2 6931777
答案2
一种使用方法awk
:
内容script.awk
:
## Process first file of arguments. Save 'id' as key and 'No' as value
## of a hash.
FNR == NR {
if ( FNR == 1 ) {
header = $2
next
}
hash[ $1 ] = $2
next
}
## Process second file of arguments. Print header in first line and for
## the rest check if first field is found in the hash.
FNR < NR {
if ( $1 in hash || FNR == 1 ) {
printf "%s %s\n", $0, ( FNR == 1 ? header : hash[ $1 ] )
}
}
像这样运行它:
awk -f script.awk File1.txt File2.txt | column -t
结果如下:
id P R S NO
gi|371443198|gb|JH556662.1| 2 2 0 7573913
gi|371440577|gb|JH559283.1| 21 19 2 6931777