【Linux】字元轉換命令join

來源:互聯網
上載者:User

標籤:style   blog   class   code   c   java   

  join 看字面上的意義 (加入/參加) 就可以知道,他是在處理兩個檔案之間的資料,而且,主要是在處理『兩個檔案當中,有 "相同資料" 的那一行,才將他加在一起』的意思。我們利用底下的簡單例子來說明:

[[email protected] ~]# join [-ti12] file1 file2選項與參數:-t  :join 預設以空格符分隔資料,並且比對『第一個欄位』的資料,      如果兩個檔案相同,則將兩筆資料聯成一行,且第一個欄位放在第一個!-i  :忽略大小寫差異;-1  :這個是數位 1 ,代表『第一個檔案要用那個欄位來分析』的意思;-2  :代表『第二個檔案要用那個欄位來分析』的意思。範例一:用 root 的身份,將 /etc/passwd 與 /etc/shadow 相關資料整合成一欄[[email protected] ~]# head -n 3 /etc/passwd /etc/shadow==> /etc/passwd <==root:x:0:0:root:/root:/bin/bashbin:x:1:1:bin:/bin:/sbin/nologindaemon:x:2:2:daemon:/sbin:/sbin/nologin==> /etc/shadow <==root:$1$/3AQpE5e$y9A/D0bh6rElAs:14120:0:99999:7:::bin:*:14126:0:99999:7:::daemon:*:14126:0:99999:7:::# 由輸出的資料可以發現這兩個檔案的最左邊欄位都是帳號!且以 : 分隔[[email protected] ~]# join -t ‘:‘ /etc/passwd /etc/shadowroot:x:0:0:root:/root:/bin/bash:$1$/3AQpE5e$y9A/D0bh6rElAs:14120:0:99999:7:::bin:x:1:1:bin:/bin:/sbin/nologin:*:14126:0:99999:7:::daemon:x:2:2:daemon:/sbin:/sbin/nologin:*:14126:0:99999:7:::# 透過上面這個動作,我們可以將兩個檔案第一欄位相同者整合成一行!# 第二個檔案的相同欄位並不會顯示(因為已經在第一行了嘛!)範例二:我們知道 /etc/passwd 第四個欄位是 GID ,那個 GID 記錄在         /etc/group 當中的第三個欄位,請問如何將兩個檔案整合?[[email protected] ~]# head -n 3 /etc/passwd /etc/group==> /etc/passwd <==root:x:0:0:root:/root:/bin/bashbin:x:1:1:bin:/bin:/sbin/nologindaemon:x:2:2:daemon:/sbin:/sbin/nologin==> /etc/group <==root:x:0:rootbin:x:1:root,bin,daemondaemon:x:2:root,bin,daemon# 從上面可以看到,確實有相同的部分喔!趕緊來整合一下![[email protected] ~]# join -t ‘:‘ -1 4 /etc/passwd -2 3 /etc/group0:root:x:0:root:/root:/bin/bash:root:x:root1:bin:x:1:bin:/bin:/sbin/nologin:bin:x:root,bin,daemon2:daemon:x:2:daemon:/sbin:/sbin/nologin:daemon:x:root,bin,daemon# 同樣的,相同的欄位部分被移動到最前面了!所以第二個檔案的內容就沒再顯示。# 請讀者們配合上述顯示兩個檔案的實際內容來比對!

  這個 join 在處理兩個相關的資料檔案時,就真的是很有協助的啦! 例如上面的案例當中,我的 /etc/passwd, /etc/shadow, /etc/group 都是有相關性的, 其中 /etc/passwd, /etc/shadow 以帳號為相關性,至於 /etc/passwd, /etc/group 則以所謂的 GID (帳號的數字定義) 來作為他的相關性。根據這個相關性, 我們可以將有關係的資料放置在一起!這在處理資料可是相當有協助的! 

  此外,需要特別注意的是,在使用 join 之前,你所需要處理的檔案應該要事先經過排序 (sort) 處理! 否則有些比對的項目會被略過呢!特別注意了!

  參考資料:http://vbird.dic.ksu.edu.tw/linux_basic/0320bash.php#join

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.