[Shell]Join使用

来源:互联网 发布:易凯软件 编辑:程序博客网 时间:2024/06/04 18:52
1. 用途

Linux join命令用于将两个文件中,指定栏位内容相同的行连接起来。找出两个文件中,指定栏位内容相同的行,并加以合并,再输出到标准输出设备。

2. 语法
  1. join [OPTION]... FILE1 FILE2
3. 参数

  1.  -a FILENUM
  2. also print unpairable lines from file FILENUM, where FILENUM is
  3. 1 or 2, corresponding to FILE1 or FILE2
  4. -e EMPTY
  5. replace missing input fields with EMPTY
  6. -i, --ignore-case
  7. ignore differences in case when comparing fields
  8. -j FIELD
  9. equivalent to '-1 FIELD -2 FIELD'
  10. -o FORMAT
  11. obey FORMAT while constructing output line
  12.  -t CHAR
  13. use CHAR as input and output field separator
  14. -v FILENUM
  15. like -a FILENUM, but suppress joined output lines
  16. -1 FIELD
  17. join on this FIELD of file 1
  18. -2 FIELD
  19. join on this FIELD of file 2
  20. --check-order
  21. check that the input is correctly sorted, even if all input
  22. lines are pairable
  23. --nocheck-order
  24. do not check that the input is correctly sorted

假设我们有两个文件:a.txt b.txt

a.txt

  1. xiaosi@Qunar:~/test$ cat a.txt
  2. aa12
  3. cc23
  4. gg46
  5. hh33

b.txt

  1. xiaosi@Qunar:~/test$ cat b.txt
  2. aa21
  3. bb82
  4. cc44
  5. dd56
  6. ff23

3.1 -a FileNum 

FileNum 指定哪个文件 (FileNum 只能取值1或者2,1表示 File1,2 表示 File2)

(1)-a 1 等价于 左连接   如果左文件的某行在右文件中没有匹配行,则在结果集行中只显示左文件行中数据

  1. xiaosi@Qunar:~/test$ join -a 1 a.txt b.txt
  2. aa 1 2 2 1
  3. cc 2 3 4 4
  4. gg 4 6
  5. hh 3 3
(2)-a 2 等价于 右连接 如果右文件的某行在左文件中没有匹配行,则在结果集行中只显示右文件行中数据
  1. xiaosi@Qunar:~/test$ join -a 2 a.txt b.txt
  2. aa 1 2 2 1
  3. bb 8 2
  4. cc 2 3 4 4
  5. dd 5 6
  6. ff 2 3
(3)无-a 参数 等价于 内连接 
  1. xiaosi@Qunar:~/test$ join a.txt b.txt
  2. aa 1 2 2 1
  3. cc 2 3 4 4

3.2 -j 指定匹配列

-j选项指定了两个文件具体按哪一列进行匹配

  1. xiaosi@Qunar:~/test$ join -j 1 a.txt b.txt
  2. aa 1 2 2 1
  3. cc 2 3 4 4

-j 1 指定两个文件按第一列进行匹配,等同于 join a.txt b.txt。

  1. xiaosi@Qunar:~/test$ join -j 2 c.txt d.txt
  2. 2 cc 3 aa 1
  3. 2 cc 3 ff 3
  4. 4 gg 6 cc 4

-j 2指定两个文件按第二列进行匹配。

备注:

c.txt 为 a.txt按第二列排序后的结果 

  1. sort -n -k 2 a.txt > c.txt
d.txt 为 b.txt按第二列排序后的结果 
  1. sort -n -k 2 b.txt > d.txt

如果指定哪一列进行连接,要根据那一列进行排序,再进行连接。


3.3 -v FileNum 反向匹配输出

输出指定文件不匹配的行,FileNum取值1或者2,1表示第一个文件,2表示第二个文件。

  1. xiaosi@Qunar:~/test$ join -v 1 a.txt b.txt
  2. gg 4 6
  3. hh 3 3
-v 1 表示输出第一个文件中不匹配的行
  1. xiaosi@Qunar:~/test$ join -v 2 a.txt b.txt
  2. bb 8 2
  3. dd 5 6
  4. ff 2 3
-v 1 表示输出第二个文件中不匹配的行



3.4 -o 格式化输出

格式化输出,指定具体哪一列输出

  1. xiaosi@Qunar:~/test$ join -o 1.1 1.2 2.2 a.txt b.txt
  2. aa 1 2
  3. cc 2 4
上面代码中表示输出第一个文件的第一列,第二列以及第二个文件的第二列







1 0
原创粉丝点击