shell join详解

首先贴一个,join --help

Usage: join [OPTION]... FILE1 FILE2
For each pair of input lines with identical join fields, write a line to
standard output.  The default join field is the first, delimited
by whitespace.  When FILE1 or FILE2 (not both) is -, read standard input.

  -a FILENUM        print unpairable lines coming from file FILENUM, where
                      FILENUM is 1 or 2, corresponding to FILE1 or FILE2
  -e EMPTY          replace missing input fields with EMPTY
  -i, --ignore-case ignore differences in case when comparing fields
  -j FIELD          equivalent to `-1 FIELD -2 FIELD'
  -o FORMAT         obey FORMAT while constructing output line
  -t CHAR           use CHAR as input and output field separator
  -v FILENUM        like -a FILENUM, but suppress joined output lines
  -1 FIELD          join on this FIELD of file 1
  -2 FIELD          join on this FIELD of file 2
      --help     display this help and exit
      --version  output version information and exit

Unless -t CHAR is given, leading blanks separate fields and are ignored,
else fields are separated by CHAR.  Any FIELD is a field number counted
from 1.  FORMAT is one or more comma or blank separated specifications,
each being `FILENUM.FIELD' or `0'.  Default FORMAT outputs the join field,
the remaining fields from FILE1, the remaining fields from FILE2, all
separated by CHAR.

Important: FILE1 and FILE2 must be sorted on the join fields.

Report bugs to <bug-coreutils@gnu.org>.

然后来理解下。

join 【命令选项】 文件1 文件2 

//命令选项可以很多, 但文件只能是两个

先从重要的开始说,join 的作用是把两个文件对一列求交集,然后输出交集部分。

来先看个基本的例子:

$ cat A.txt

1 abc 20
2 ccc 22
3 sed 11
4 xxx 23
$ cat B.txt

1 h 0
2 x 2
3 b 3
5 s 3
$ join A.txt B.txt

1 abc 20 h 0
2 ccc 22 x 2
3 sed 11 b 3

为什么得到上面的结果,因为join默认使用空格作为分隔符(可以使用-t设定分割符),使用第一行作为主列(用于求交集的列)。

如果要将所有内容都出来呢,不管有没有配对。可以使用-a命令。

$ join -a1 A.txt B.txt
1 abc 20 h 0
2 ccc 22 x 2
3 sed 11 b 3
2 xxx 23

//可以发现,A.txt中没有配对的内容在文件的末尾被输出了。

同样可以把A.txt 和 B.txt都输出来。

$ join -a1 -a2 A.txt B.txt
1 abc 20 h 0
2 ccc 22 x 2
3 sed 11 b 3
2 xxx 23
5 s 3

 

但是这时候却发现,排版和我们想的不一样。最后两行根本分不清是来战A.txt还是B.txt。

这时候就要用-o命令和-e命令了。

$ join -a1 -a2 -e"_" -o'1.1 1.2 1.3 2.1 2.2 2.3' A.txt B.txt
1 abc 20 1 h 0
2 ccc 22 2 x 2
3 sed 11 3 b 3
2 xxx 23 _ _ _
_ _ _ 5 s 3

其中-e表示如果元素不存在时填充什么, -o 表示以哪种形式输出(1.1 表示文件1中的第一列)。

 

如何求A.txt中有,而B.txt中没有的呢?

这时候就需要使用-v了

join -v1 A.txt B.txt
2 xxx 23

输出了A中有而B中没有的部分。

 

另外-i 忽略大小写

-j x 相当于同时写了-1x -2x

也就是指定两个文件的x列作为主列。

 

join内部是怎么实现的呢,我们来看join中的重要要求,每个文件的主列都必须是排好序的!!!

是不是一下就知道了join是怎么实现的了,就是两个有序的数组求交集嘛。是不是对join的复杂度也有了更深的理解。忽略列的大小的情况下,O(n + m)就可以完成了,其中n为文件1的行数,m是文件2的行数。

 

posted @ 2017-09-28 17:26  chenhuan001  阅读(2538)  评论(0编辑  收藏  举报