天天看點

[Shell]Join使用

版權聲明:本文為部落客原創文章,未經部落客允許不得轉載。 https://blog.csdn.net/SunnyYoona/article/details/52981239

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. aa 1 2

  3. cc 2 3

  4. gg 4 6

  5. hh 3 3

b.txt

  1. xiaosi@Qunar:~/test$ cat b.txt

  2. aa 2 1

  3. bb 8 2

  4. cc 4 4

  5. dd 5 6

  6. ff 2 3

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

上面代碼中表示輸出第一個檔案的第一列,第二列以及第二個檔案的第二列

繼續閱讀