通过匹配另一个文件中的列来从文件中子集行
我有制表符分隔的文件,文件的文件1和文件2。我想创建子集划分由来自文件1的所有四列的行的文件3中,塔1和2从文件2匹配,该file1的看起来像:
1 17626 A G
1 20184 G A
1 108826 C G
1 108929 G C
而且,file2为:
1 17626
1 20184
我想要文件 3 中的输出如下
1 17626 A G
1 20184 G A
我已经尝试了以下代码查看以前的问题:
awk -F 't' 'NR==FNR{c[$1$2]++;next};c[$1$2]' file2 file1 > file3
awk -F 't' 'NR==FNR{c[$1$2]++;next};c[$1$2] > 0' file2 file1 > file3
awk -F 't' 'NR==FNR{a[$1$2]; next} FNR==1 || $1$2 in a' file2 file1 > file3
从上面的两个命令,我得到一个空文件。而且,使用最后一个命令,我只得到一行输出,而不是预期的两行。
回答
使用您显示的样本,请尝试以下操作。
awk 'FNR==NR{arr[$1,$2];next} (($1,$2) in arr)' Input_file2 Input_file1
如果它的制表符被分隔,请尝试以下操作:
awk 'BEGIN{FS=OFS="t"} FNR==NR{arr[$1,$2];next} (($1,$2) in arr)' file2 file1
说明:为以上添加详细说明。
awk ' ##Starting awk program from here.
FNR==NR{ ##Checking condition FNR==NR which will be TRUE when file2 is being read.
arr[$1,$2] ##Creating array arr with index of $1 and $2 here.
next ##next will skip all further statements from here.
}
(($1,$2) in arr) ##Checking if $1,$2 is present in arr then print line.
' Input_file2 Input_file1 ##Mentioning Input_file names here.