如何使用awk根据前三列合并两个文件 [英] How to merge two files based on the first three columns using awk
本文介绍了如何使用awk根据前三列合并两个文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想使用前三列作为键将两个文件逐行合并为一个文件.示例:
I wanted to merge two files into a single one line by line using the first three columns as a key. Example:
file1.txt
file1.txt
a b c 1 4 7
x y z 2 5 8
p q r 3 6 9
file2.txt
file2.txt
p q r 11
a b c 12
x y z 13
我对以上两个文件的期望输出是:
My desired output for the above two files is:
a b c 1 4 7 12
x y z 2 5 8 13
p q r 3 6 9 11
每个文件中的列数不是固定的,它可能随行而变化.另外,每个文件中我的行数超过了27K.
The number of columns in each file is not fixed, it can vary from line to line. Also, I got more than 27K lines in each file.
未订购.他们唯一的事情是两个文件的前三个字段都相同.
They are not ordered. They only thing is that the first three fields are the same for both files.
推荐答案
加入前三个字段,其中字段数是可变的(四个或更多):
Join on the first three fields where the number of fields are variable (four or more):
{
# get the forth field until the last
for (i=4;i<=NF;i++)
f=f$i" "
# concat fields
arr[$1OFS$2OFS$3]=arr[$1OFS$2OFS$3]f;
# reset field string
f=""
}
END {
for (key in arr)
print key, arr[key]
}
运行方式:
$ awk -f script.awk file1 file2
a b c 1 4 7 12
p q r 3 6 9 11
x y z 2 5 8 13
这篇关于如何使用awk根据前三列合并两个文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文