比较不同的列的两个文件和打印不同的列 [英] Compare two files of different columns and print different columns
本文介绍了比较不同的列的两个文件和打印不同的列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想比较的文件2 的第2个柱的文件1 的第1列。如果他们是平等的,我想补充的文件1 的第2列的文件2 的,如图中的 output.txt的的
I want to compare 2nd column of file2 with 1st column of file1. If they are equal i want to add the 2nd column of file1 to file2 as shown in output.txt.
的文件2 的
chr5 ENST00000514151 utr5 0 +
chr5 ENST00000512281 utr5 0 +
chr5 ENST00000512281 utr5 0 +
chr5 ENST00000512281 utr5 0 +
的文件1 的
ENST00000512281 a
ENST00000504031 b
ENST00000776348 c
的 output.txt的的
chr5 a ENST00000512281 utr5 0 +
chr5 a ENST00000512281 utr5 0 +
chr5 a ENST00000512281 utr5 0 +
我能够将文件以
awk 'NR==FNR{a[$1];next}$2 in a{print}' file1 file2
这给出以下的输出:
chr5 ENST00000512281 utr5 0 +
chr5 ENST00000512281 utr5 0 +
chr5 ENST00000512281 utr5 0 +
但我不知道如何file1的第二柱添加到输出。
But I do not know how to add the 2nd colum of file1 into the output.
推荐答案
您可以 $ 2
的值存储在文件1
到使用数组 A [$ 1 = $ 2
。所以,你可以尝试:
You can store the value of $2
in file1
into the array using a[$1]=$2
. So you could try:
awk '
NR==FNR{
a[$1]=$2 ; next }
$2 in a {
$1=$1 FS a[$2]
print
}' file1 file2
输出:
chr5 b ENST00000504031 utr5 0 +
chr5 b ENST00000504031 utr5 0 +
chr5 a ENST00000512281 utr5 0 +
chr5 a ENST00000512281 utr5 0 +
chr5 a ENST00000512281 utr5 0 +
说明:
- 这会修改
$ 1
在文件2
使用$ 1 = $个外勤一个[$ 2]
,其中FS
是默认的字段分隔符,这是一个空间..然后重建记录,例如,它可以通过<$ C $打印C>打印后.. - 的
打印
可以简化为一个1
如果需要的话..就像$ 2 {$ 1美元= $ 1 FS一[$ 2]} 1
- 请注意,这在重建
文件2
的记录,因而空格或制表符的序列,将被截断,以输出一个空格。为了保持原来的格式在文件2
人们可以使用拆分()
功能了GNU AWK版本4 ..
- This modifies
$1
infile2
using$1=$1 FS a[$2]
whereFS
is the default field separator, which is a space.. and then rebuilds the record, such that it can be printed byprint
later.. - The
print
can be simplified to a1
if desired.. Like$2 in a { $1=$1 FS a[$2] }1
- Note that this rebuilds the record in
file2
and thus any sequences of spaces or tabs will be truncated to a single space in the output. To keep the original formatting infile2
one could use thesplit()
function in Gnu Awk version 4..
这篇关于比较不同的列的两个文件和打印不同的列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文