join:按照两个文件的相同字段合并

xiaohai 2021-06-09 10:56:16 1840人围观 标签: Linux 
简介 join命令针对每一对具有相同内容的行整合为一行,默认情况下是把输入的第一个字段作为连接字段,字段之间用空格隔开。
说明

  join命令针对每一对具有相同内容的行整合为一行,默认情况下是把输入的第一个字段作为连接字段,字段之间用空格隔开。

格式

  join [option] [file1] [file2]

常用参数说明
  • -a 文件号:输出文件中不匹配的行,文件号可选值为1或2,分表表示文件1或文件2
  • -i:比较时忽略大小写
  • -1 字段:以第一个文件的指定字段为基础进行合并
  • -2 字段:以第二个文件的指定字段为基础进行合并
示例

1、对两个文件进行合并

[root@localhost ~]# cat join1.txt 
xiaohai 21
zhang 22
li 29
wang 33
[root@localhost ~]# cat join2.txt 
wang beijing
zhang shanghai
li chengdu
xiaohai taikong
[root@localhost ~]# join join1.txt join2.txt #合并的时候,要求对这两个文件先进行排序
join: join1.txt:3: is not sorted: li 29
join: join2.txt:3: is not sorted: li chengdu
zhang 22 shanghai
li 29 chengdu
[root@localhost ~]# sort join1.txt > join1.txts
[root@localhost ~]# sort join2.txt > join2.txts
[root@localhost ~]# 
[root@localhost ~]# cat join1.txts
li 29
wang 33
xiaohai 21
zhang 22
[root@localhost ~]# cat join2.txts 
li chengdu
wang beijing
xiaohai taikong
zhang shanghai
[root@localhost ~]# 
[root@localhost ~]# join join1.txts join2.txts #排序后的文件进行合并
li 29 chengdu
wang 33 beijing
xiaohai 21 taikong
zhang 22 shanghai

2、-i参数使用,忽略大小写

[root@localhost ~]# vim join2.txt #将zhang改成Zhang
[root@localhost ~]# sort join2.txt > join2.txts #重新排序
[root@localhost ~]# cat join2.txts 
li chengdu
wang beijing
xiaohai taikong
Zhang shanghai
[root@localhost ~]# 
[root@localhost ~]# join -i join1.txts join2.txts 
li 29 chengdu
wang 33 beijing
xiaohai 21 taikong
zhang 22 shanghai

3、指定按照某个字段进行合并

[root@localhost ~]# cat join1.txt #修改该文件,在前面加上一列序号
1 xiaohai 21
2 zhang 22
3 li 29
4 wang 33
[root@localhost ~]# sort -t " " -k 2 join1.txt > join1.txts #按照第二列进行排序,并写入到新文件
[root@localhost ~]# join join1.txts join2.txts -1 2 #指定第一个文件的第二个字段
li 3 29 chengdu
wang 4 33 beijing
xiaohai 1 21 taikong