Linux 按列合并两个文件 [英] Linux Combine two files by column
本文介绍了Linux 按列合并两个文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试合并两个文件,如下所示(交集)
I am trying to combine two files as below (Intersection)
ID Name Telephone
1 John 011
2 Sam 013
3 Jena 014
4 Peter 015
第二个文件Test2.txt
Second file Test2.txt
1 Test1 Test2
2 Test3 Test4
3 Test5 Test6
4 Test7 Test8
5 Test7 Test8
6 Test7 Test8
7 Test7 Test8
8 Test7 Test8
9 Test7 Test8
然后是最终结果
ID Name Telephone Remark1 Remark2
1 John 011 Test1 Test2
2 Sam 013 Test3 Test4
3 Jena 014 Test5 Test6
4 Peter 015 Test7 Test8
我喜欢这个,如下所示,
I did like this as below,
awk -F" " '
{key = $1 }
NR == 1 {header = key}
!(key in result) {result[key] = $0; next}
{ for (i=2; i <= NF; i++) result[key] = result[key] FS $i }
END {
print result[header]
delete result[header]
PROCINFO["sorted_in"] = "@ind_str_asc"
for (key in result) print result[key]
}
' Test1.txt Test2.txt > result.txt
我只是注意到这是联盟集.包括所有数据Test1和Test2.
And I just notice that this is Union set. Including all data Test1 and Test2.
我只想将 Intersection 情况显示为我预期的结果.(1, 2 ,3 ,4) 仅
I would like to show only for Intersection case as what I expected result. (1, 2 ,3 ,4) only
你们有什么想法吗?谢谢!
Do you guys have any idea? Thanks!
推荐答案
$ awk -v OFS=' ' '
NR==1 { print $0, "Remark1", "Remark2"; next }
NR==FNR { a[$1]=$0; next }
$1 in a { print a[$1], $2, $3 }
' Test1.txt Test2.txt
ID Name Telephone Remark1 Remark2
1 John 011 Test1 Test2
2 Sam 013 Test3 Test4
3 Jena 014 Test5 Test6
4 Peter 015 Test7 Test8
这篇关于Linux 按列合并两个文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文