0%

存同求异 join

存同求异 join

.. note::
劝君莫惜金缕衣,劝君惜取少年时。

  • 杜秋娘《金缕衣》

Linux join命令用于将两个文件中指定栏位内容相同的行连接起来。

找出两个文件中,指定栏位内容相同的行,并加以合并,再输出到标准输出设备。

类似于SQL的JOIN操作

官方解释为:

join - join lines of two files on a common field

语法为:

1
$  join [OPTION]... FILE1 FILE2

这个命令的参数还是有一些的,不过基本默认的足够使用了。

join实例

最简单的连接两个文件。

首先看一下两个文件的内容,然后进行join操作。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# 查看file1、file2 的文件内容:
$ cat file1
Zhangsan age 14
Lisi age 15
Wangwu age 16

$ cat file2
Zhangsan score 80
Lisi score 90
Wangwu score 85

# 使用join命令
$ join file1 file2
Zhangsan age 14 score 80
Lisi age 15 score 90
Wangwu age 16 score 85

# 交互两个文件的顺序
$ join file2 file1
Zhangsan score 80 age 14
Lisi score 90 age 15
Wangwu score 85 age 16

可以看到交换顺序对输出是有影响的,会影响到最终的输出内容。

不同的栏内容进行join操作

而如果两个文件的内容不同,那么在进行join操作时会有警告信息输出,如下所示:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
$ cat file1       
Jialiu age 15
Zhangsan age 14
Lisi age 15
Wangwu age 16
$ cat file2
Zhangsan score 80
Lisi score 90
Wangwu score 85
Jialiu score 88
$ join file1 file2
join: file1:3: is not sorted: Lisi age 15
join: file2:2: is not sorted: Lisi score 90
Zhangsan age 14 score 80
Lisi age 15 score 90
Wangwu age 16 score 85
$ join file2 file1
join: file2:2: is not sorted: Lisi score 90
join: file1:3: is not sorted: Lisi age 15
Zhangsan score 80 age 14
Lisi score 90 age 15
Wangwu score 85 age 16
处无为之事,行不言之教;作而弗始,生而弗有,为而弗恃,功成不居!