2017-08-01 48 views
0

創建新的文件,比方說,我有「文件1」,如下內容:awk來從非現有的第一列

123|abc|def| 
    456|ghi|jkl| 
    789|mno|pqr| 

而且我有「文件2」如下內容:

123|abc|def| 
    456|ghi|jkl| 
    789|mno|pqr| 
    134|rst|uvw| 

正如您所見,文件1中不存在「134」,因此,我的shell腳本應創建一個文件3,其中包含如下內容。

134|rst|uvw| 

我該如何做到這一點?

+1

Stackoverflow不是代碼編寫服務。請告訴我們你已經嘗試了什麼。請參閱:[如何創建最小,完整和可驗證示例。](https://stackoverflow.com/help/mcve)。你也許只是在尋找像'grep -vf file1 file2> file3'這樣簡單的東西# – Jedi

+0

我只需要知道什麼命令最好使用,而不是整個代碼 – MFAY

+0

[可以在一個文件中找到行的快速方法不在另一個?](https://stackoverflow.com/questions/18204904/fast-way-of-finding-lines-in-one-file-that-are-not-in-another) – Jedi

回答

1

在AWK:

$ awk -F\| 'NR==FNR{a[$1];next}$1 in a==0' file1 file2 # > file3 
134|rst|uvw| 

解釋:

$ awk -F\| '  # field separator is | 
NR==FNR {  # process first file 
    a[$1]  # store the velue in the first field to hash a 
    next   # next record 
}    # below, processing the second file 
$1 in a==0  # if first field is not found in the hash a, output the record 
' file1 file2 # > file3 redirect to file3 if desired, else it's on your screen 

基本上它存儲的file1第一字段值進行散列a和在處理file2打印出其中在未找到第一個字段中記錄a。所以它與grep的解決方案不同,它比較整個記錄,而不僅僅是一個字段。