版權聲明:本文為部落客原創文章,未經部落客允許不得轉載。 https://blog.csdn.net/SunnyYoona/article/details/52981239
1. 用途
Linux join指令用于将兩個檔案中,指定欄位内容相同的行連接配接起來。找出兩個檔案中,指定欄位内容相同的行,并加以合并,再輸出到标準輸出裝置。
2. 文法
-
join [OPTION]... FILE1 FILE2
3. 參數
-
-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
假設我們有兩個檔案:a.txt b.txt
a.txt
-
xiaosi@Qunar:~/test$ cat a.txt
-
aa 1 2
-
cc 2 3
-
gg 4 6
-
hh 3 3
b.txt
-
xiaosi@Qunar:~/test$ cat b.txt
-
aa 2 1
-
bb 8 2
-
cc 4 4
-
dd 5 6
-
ff 2 3
3.1 -a FileNum
FileNum 指定哪個檔案 (FileNum 隻能取值1或者2,1表示 File1,2 表示 File2)
(1)-a 1 等價于 左連接配接 如果左檔案的某行在右檔案中沒有比對行,則在結果集行中隻顯示左檔案行中資料
-
xiaosi@Qunar:~/test$ join -a 1 a.txt b.txt
-
aa 1 2 2 1
-
cc 2 3 4 4
-
gg 4 6
-
hh 3 3
(2)-a 2 等價于 右連接配接 如果右檔案的某行在左檔案中沒有比對行,則在結果集行中隻顯示右檔案行中資料
-
xiaosi@Qunar:~/test$ join -a 2 a.txt b.txt
-
aa 1 2 2 1
-
bb 8 2
-
cc 2 3 4 4
-
dd 5 6
-
ff 2 3
(3)無-a 參數 等價于 内連接配接
-
xiaosi@Qunar:~/test$ join a.txt b.txt
-
aa 1 2 2 1
-
cc 2 3 4 4
3.2 -j 指定比對列
-j選項指定了兩個檔案具體按哪一列進行比對
-
xiaosi@Qunar:~/test$ join -j 1 a.txt b.txt
-
aa 1 2 2 1
-
cc 2 3 4 4
-j 1 指定兩個檔案按第一列進行比對,等同于 join a.txt b.txt。
-
xiaosi@Qunar:~/test$ join -j 2 c.txt d.txt
-
2 cc 3 aa 1
-
2 cc 3 ff 3
-
4 gg 6 cc 4
-j 2指定兩個檔案按第二列進行比對。
備注:
c.txt 為 a.txt按第二列排序後的結果
-
sort -n -k 2 a.txt > c.txt
d.txt 為 b.txt按第二列排序後的結果
-
sort -n -k 2 b.txt > d.txt
如果指定哪一列進行連接配接,要根據那一列進行排序,再進行連接配接。
3.3 -v FileNum 反向比對輸出
輸出指定檔案不比對的行,FileNum取值1或者2,1表示第一個檔案,2表示第二個檔案。
-
xiaosi@Qunar:~/test$ join -v 1 a.txt b.txt
-
gg 4 6
-
hh 3 3
-v 1 表示輸出第一個檔案中不比對的行
-
xiaosi@Qunar:~/test$ join -v 2 a.txt b.txt
-
bb 8 2
-
dd 5 6
-
ff 2 3
-v 1 表示輸出第二個檔案中不比對的行
3.4 -o 格式化輸出
格式化輸出,指定具體哪一列輸出
-
xiaosi@Qunar:~/test$ join -o 1.1 1.2 2.2 a.txt b.txt
-
aa 1 2
-
cc 2 4
上面代碼中表示輸出第一個檔案的第一列,第二列以及第二個檔案的第二列