LInux之Join命令

介绍

在Linux中,如果你想要把两个文件按照列合并起来,比如一个文件存有一列学号一列姓名,另一个文件存有一列学号一列成绩,这个时候使用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        also print unpairable lines 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
  --check-order     check that the input is correctly sorted, even
                      if all input lines are pairable
  --nocheck-order   do not check that the input is correctly sorted
  --header          treat the first line in each file as field headers,
                      print them without trying to pair them
      --help     display this help and exit
      --version  output version information and exit

实例

先创建两个演示文件,待合并

 $ cat file1
1   Alice
2   Bob
3   cheryl
4   Doghead
 $ cat file2
1   60.0
2   70.0
3   80.0
4   90.0

然后使用join,一步到位

 $ join file1 file2
1 Alice 60.0
2 Bob 70.0
3 cheryl 80.0
4 Doghead 90.0

join默认以第一列为匹配列,也可以自己指定,例如指定第二列

$ join -j 2 file1 file2

甚至可以分别指定两个文件的不同列作为匹配,例如指定第一个文件的第一列和第二个文件的第一列(这个例子中匹配别的列没有结果)

 $ join -1 1 -2 1 file1 file2
1 Alice 60.0
2 Bob 70.0
3 cheryl 80.0
4 Doghead 90.0

当须要将多个格式同样的文件join到一起(join接受的是两个文件的指令),此时我们可以使用管道和字符“-"来实现
例如,join四个文件

join file1 file2 | join - file3 | join - file4 

最后,注意join需要有指定的对应列,实际使用中需要根据数据形式来灵活使用。

posted @ 2020-01-10 15:09  MrDoghead  阅读(646)  评论(0编辑  收藏  举报