join命令

功能说明:

将两个文件中,指定栏位内容相同的行连接起来。

语法:join [-i][-a<1|2>][-e<string>][-o<格式>] [-t<字符>][-v<1|2>][-1<栏位>][-2<栏位>][--help] [--version][文件1][文件2]

补充说明:

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

参数:

-a<1|2>  除了显示原来的输出内容之外,还显示指令文件中没有相同栏位的行。

-e<字符串[文件1][文件2]中找不到指定的栏位,则在输出中填入选项中的字符串。

-i--igore-case  比较栏位内容时,忽略大小写的差异。

-o<格式按照指定的格式来显示结果。

-t<字符使用栏位的分隔字符。

-v<12>  -a相同,但是只显示文件中没有相同栏位的行。

-1<栏位连接[文件1]指定的栏位。

-2<栏位连接[文件2]指定的栏位。

--help  显示帮助。

--version  显示版本信息。

指定输出字段:

-o <FILENO.FIELDNO> ...

其中fileno=1表示第一个文件,fileno=2表示第二个文件,fieldno表示字段序号,从1开始编号。默认会全部输出,但关键字列只输出一次。

比如:-o 1.1 1.2 2.2 表示输出第一个文件的第一个字段、第二个字段,第二个文件的第二个字段。

使用示例

示例一 内连接(忽略不匹配的行)

不指定任何参数的情况下使用join命令,就相当于数据库中的内连接,关键字不匹配的行不会输出。

[root@rhel55 linux]# cat month_cn.txt

1       一月

2       二月

13      十三月,故意的

[root@rhel55 linux]# cat month_en.txt

1       January

2       February

14      MonthUnknown

注:注意两个文件的内容,中文版的多了十三月,英文版的多了14月,这纯粹是为了方便演示。

[root@rhel55 linux]# join month_cn.txt month_en.txt 

1 一月 January

2 二月 February

[root@rhel55 linux]#

示例二 左连接(又称左外连接,显示左边所有记录)

显示左边文件中的所有记录,右边文件中没有匹配的显示空白。

[root@rhel55 linux]# join -a1 month_cn.txt month_en.txt

1 一月 January

2 二月 February

13 十三月,故意的

[root@rhel55 linux]#

示例三 右连接(又称右外连接,显示右边所有记录)

显示右边文件中的所有记录,左边文件中没有匹配的显示空白。

[root@rhel55 linux]# join -a2 month_cn.txt month_en.txt 

1 一月 January

2 二月 February

14 MonthUnknown

[root@rhel55 linux]#

示例四 全连接(又称全外连接,显示左边和右边所有记录)

[root@rhel55 linux]# join -a1 -a2 month_cn.txt month_en.txt

1 一月 January

2 二月 February

13 十三月,故意的

14 MonthUnknown

[root@rhel55 linux]#

示例五 指定输出字段

比如参数 -o 1.1 表示只输出第一个文件的第一个字段。

[root@rhel55 linux]# join -o 1.1 month_cn.txt month_en.txt

1

2

[root@rhel55 linux]# join -o 1.1 2.2 month_cn.txt month_en.txt  

1 January

2 February

[root@rhel55 linux]# join -o 1.1 2.2 1.2 month_cn.txt month_en.txt

1 January 一月

2 February 二月

[root@rhel55 linux]# join -o 1.1 2.2 1.2 1.3 month_cn.txt month_en.txt 

字段1.3并不存在

1 January 一月

2 February 二月

[root@rhel55 linux]#

示例六 指定分隔符

[root@rhel55 linux]# join -t ':' /etc/passwd /etc/shadow

root:x:0:0:root:/root:/bin/bash:$1$K8WSIAfQ$9i1h6a4V1XeIn0lv.CT53/:14833:0:99999:7:::

bin:x:1:1:bin:/bin:/sbin/nologin:*:14833:0:99999:7:::

原文

http://www.cnblogs.com/agilework/archive/2012/04/18/2454877.html

原文地址:https://www.cnblogs.com/mydomain/p/3034291.html