簡體   English   中英

Awk從不存在的第一列創建新文件

[英]Awk to create new file from non existing first column

假設我有“文件1”,其內容如下:

    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|

我該如何實現?

在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解決方案,后者比較整個記錄,而不僅僅是一個字段。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM