使用 awk 基于两列连接文件
Join files based on two columns using awk
我有以下两个文件;
$ cat file1
1 4
2 5
3 6
$ cat file2
4 2 N1
4 1 Y1
6 2 N2
6 3 Y2
2 5 Y3
我对file2
的第三栏感兴趣。所以我想根据两个第一列(ID 列)加入两个文件。经过大量搜索(例如here, or )我尝试了一些东西并且原则上有效;
awk 'FNR==NR{a[,];next}; (, ) in a || (, ) in a{print }' file1 file2
Y1
Y2
Y3
或者,
awk 'FNR==NR{a[,]=;next}; (, ) in a || (, ) in a{print [=12=], a[,]}' file2 file1
1 4
2 5 Y3
3 6
然而并不是我想要的确切输出;
1 4 Y1
2 5 Y3
3 6 Y2
file1
中 ID 的顺序很重要,因为例如第一列是男性,第二列是女性。 file2
中的列可能是男性或女性。
像这样:
awk 'NR==FNR{s[ OFS ]; next}
( OFS ) in s {
print , ,
}
( OFS ) in s {
print , ,
}' file file2
不是很短,但够用了:
$ awk 'FNR==NR{a[,]= FS ;a[,]=a[,];next}; (,) in a || (,) in a{print a[,],}' file1 file2
1 4 Y1
3 6 Y2
2 5 Y3
选择:
$ awk 'FNR==NR{a[,]= FS ;next}; {pr=0};(,) in a {pr=a[,]};(,) in a{pr=a[,]};pr{print pr,}' file1 file2
我有以下两个文件;
$ cat file1
1 4
2 5
3 6
$ cat file2
4 2 N1
4 1 Y1
6 2 N2
6 3 Y2
2 5 Y3
我对file2
的第三栏感兴趣。所以我想根据两个第一列(ID 列)加入两个文件。经过大量搜索(例如here,
awk 'FNR==NR{a[,];next}; (, ) in a || (, ) in a{print }' file1 file2
Y1
Y2
Y3
或者,
awk 'FNR==NR{a[,]=;next}; (, ) in a || (, ) in a{print [=12=], a[,]}' file2 file1
1 4
2 5 Y3
3 6
然而并不是我想要的确切输出;
1 4 Y1
2 5 Y3
3 6 Y2
file1
中 ID 的顺序很重要,因为例如第一列是男性,第二列是女性。 file2
中的列可能是男性或女性。
像这样:
awk 'NR==FNR{s[ OFS ]; next}
( OFS ) in s {
print , ,
}
( OFS ) in s {
print , ,
}' file file2
不是很短,但够用了:
$ awk 'FNR==NR{a[,]= FS ;a[,]=a[,];next}; (,) in a || (,) in a{print a[,],}' file1 file2
1 4 Y1
3 6 Y2
2 5 Y3
选择:
$ awk 'FNR==NR{a[,]= FS ;next}; {pr=0};(,) in a {pr=a[,]};(,) in a{pr=a[,]};pr{print pr,}' file1 file2