天天看點

Linux 指令整理 —— 檔案操作——Join

工作中如何讓自己變得強大?向周圍人學習!

同僚求助Linux下倆檔案相同部分做篩選,資料檔案很大,如何操作。終于發現牛人,我就順道偷師學藝。

相關連結: 

Linux 指令整理 —— 基本操作 

Linux 指令整理 —— 使用者管理 

一、一般關聯

比方說有兩個檔案:

寫道 $ cat 1

a 100

b 200

c 300

d 500

$ cat 2

c 2012-03-01

d 2012-05-01

a 2012-01-01

 我想要兩個檔案中互相比對的部分,也就是a、c、d部分。

寫道 $ join 1 2

c 300 2012-03-01

d 500 2012-05-01

但實際上隻有c、d兩部分,因為要使用JOIN,帶關聯檔案中首列必須先做好排序。具體看下面的參數說明。

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 顯示此幫助資訊并離開

--version 顯示版本資訊并離開

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 <[email protected]>.

 原來使用JOIN,類似于Database中的join一樣,預設首列作為主外鍵自動關聯。

Linux 指令整理 —— 檔案操作——Join

JOIN還有很多參數,自己去領悟了。

Linux 指令整理 —— 檔案操作——Join

二、特殊分隔符

“空格”是預設分隔符,如果要使用特定符号作為分隔符,譬如“,”,可以用“-t”參數:

寫道 $ join 1 2 -t ,

c,300,2012-03-01

d,500,2012-05-01

三、特定字段關聯

如果需要關聯的字段不是首列,可以使用“-j”參數,以及“-1”,“-2”支出前後兩個檔案的具體列号:

寫道 cat 1

a,100

b,200

c,300

d,500

$ cat 3

f,c

m,d

$ join 1 3 -t , -1 1 -2 2

c,300,f

d,500,m

 檔案3的關聯字段是第二列,是以有了上面的這種寫法。

四,顯示特定列

如果我隻需要特定列輸出,不關心檔案原有部分,可以用“-o”參數。

寫道 $ join 1 2 -t , -o 1.1,1.2,2.2

c,300,2012-03-01

d,500,2012-05-01

 注意待顯示列,用“,”分割。

還有幾個參數,請大家自悟吧!

Linux 指令整理 —— 檔案操作——Join

目前這些,已經夠用了!

Linux 指令整理 —— 檔案操作——Join

相關連結: 

Linux 指令整理 —— 基本操作 

Linux 指令整理 —— 使用者管理 

繼續閱讀