join 是 Linux 中用于按字段将两个文件进行连接的命令,功能类似 SQL 的 JOIN。
| 参数 | 说明 |
|---|---|
| -1 N | 指定 file1 用第 N 字段作为连接键 |
| -2 N | 指定 file2 用第 N 字段作为连接键 |
| -t CHAR | 设置字段分隔符(如 -t , 表示用逗号) |
| -o FORMAT | 指定输出字段的格式,例如:-o 0 1.2 2.3 |
| -a 1 | 输出 file1 中所有行(即使没有匹配),相当于 LEFT OUTER JOIN |
| -a 2 | 输出 file2 中所有行(即使没有匹配),相当于 RIGHT OUTER JOIN |
| -a 1 -a 2 | 输出所有行(匹配和未匹配),相当于 FULL OUTER JOIN |
| -e STRING | 指定空字段填充值,用于 -a 显示未匹配时 |
| -i | 忽略大小写(等价于 --ignore-case) |
| -v 1 | 仅显示 file1 中未匹配的行 |
| -v 2 | 仅显示 file2 中未匹配的行 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
apluser@FengYeHong-HP:0725$ cat students1.txt 101 Alice 102 Bob 103 Carol apluser@FengYeHong-HP:0725$ cat scores1.txt 101 80 102 90 104 95 apluser@FengYeHong-HP:0725$ cat students2.txt 101,Alice 102,Bob 103,Carol apluser@FengYeHong-HP:0725$ cat scores2.txt Alice,80 Bob,90 fengyehong,95 |
‘默认情况下使用文件的第1列进行join
|
1 2 3 |
apluser@FengYeHong-HP:0725$ join students1.txt scores1.txt 101 Alice 80 102 Bob 90 |
|
1 2 3 4 5 6 |
apluser@FengYeHong-HP:0725$ join -1 1 -2 1 students1.txt scores1.txt 101 Alice 80 102 Bob 90 apluser@FengYeHong-HP:0725$ join -t, -1 2 -2 1 students2.txt scores2.txt Alice,101,80 Bob,102,90 |
|
1 2 3 4 5 6 7 8 |
apluser@FengYeHong-HP:0725$ join -a 1 students1.txt scores1.txt 101 Alice 80 102 Bob 90 103 Carol apluser@FengYeHong-HP:0725$ join -a 2 students1.txt scores1.txt 101 Alice 80 102 Bob 90 104 95 |
|
1 2 3 4 5 |
apluser@FengYeHong-HP:0725$ join -a 1 -a 2 students1.txt scores1.txt 101 Alice 80 102 Bob 90 103 Carol 104 95 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
apluser@FengYeHong-HP:0725$ cat address1.txt 101 地球 火星 102 水星 金星 104 木星 土星 apluser@FengYeHong-HP:0725$ join students1.txt address1.txt 101 Alice 地球 火星 102 Bob 水星 金星
apluser@FengYeHong-HP:0725$ join -o 1.2 2.2 2.3 students1.txt address1.txt Alice 地球 火星 Bob 水星 金星 apluser@FengYeHong-HP:0725$ join -o 1.2,2.2,2.3 students1.txt address1.txt Alice 地球 火星 Bob 水星 金星 |
|
1 2 3 4 |
apluser@FengYeHong-HP:0725$ join -v 1 students1.txt address1.txt 103 Carol apluser@FengYeHong-HP:0725$ join -v 2 students1.txt address1.txt 104 木星 土星 |
|
1 2 3 |
apluser@FengYeHong-HP:0725$ join -v 1 -v 2 students1.txt address1.txt 103 Carol 104 木星 土星 |