[英]How to append a column from another file to an existing file using 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.