我有兩個檔案,每個檔案有 3 列。我想將 file1 的第 3 列的元素與 file2 的第 3 列匹配。如果匹配,則將 file1 的整行替換為與 file2 中的匹配對應的行,否則移至下一行。
下面是示例: 在 file2 中,第 3 列元素 reg[2] 和 reg[9][9] 存在于 file1 的第 3 列中。因此,file1 的相應行將替換為 file2 中的行。
檔案1:
Nancy Owen reg[2]
Nancy Owen reg[4_8]
Nancy Owen reg[7]
Nancy Owen reg[9][9]
Nancy Owen reg[54]
檔案2:
Done Approval reg[9][9]
Nancy Owen reg[10_8]
Nancy Owen reg[4][10]
Done Approval reg[2]
期望的輸出
Done Approval reg[2]
Nancy Owen reg[4_8]
Nancy Owen reg[7]
Done Approval reg[9][9]
Nancy Owen reg[54]
嘗試的代碼:
awk -F, 'NR==FNR{a[$3]=$0;next;}a[$3]{$0=a[$3]}1' file2 file1
我仍然是使用 oneliner awk 命令的新手。我在上面的代碼中肯定做錯了什么。我要做的是將第三列以鍵的形式并將整行作為值。如果 key 存在于 file1 的 column3 中,則將 fil1 當前行替換為 file2 中的當前值。否則跳過并移至下一行。
uj5u.com熱心網友回復:
我會AWK按照以下方式使用 GNU,讓file1.txt內容成為
Nancy Owen reg[2]
Nancy Owen reg[4_8]
Nancy Owen reg[7]
Nancy Owen reg[9][9]
Nancy Owen reg[54]
和file2.txt內容是
Done Approval reg[9][9]
Nancy Owen reg[10_8]
Nancy Owen reg[4][10]
Done Approval reg[2]
然后
awk 'FNR==NR{arr[$3]=$0;next}{print($3 in arr?arr[$3]:$0)}' file2.txt file1.txt
輸出
Done Approval reg[2]
Nancy Owen reg[4_8]
Nancy Owen reg[7]
Done Approval reg[9][9]
Nancy Owen reg[54]
說明:從處理開始file2.txt,將每一行存盤arr在 key 下的陣列中,即第 3 列 ( $3) 值,不做任何其他事情(因此next使用),然后處理file1.txt如果 arr 鍵 ( ) 中存在第 3 個值,則$3 in arr執行print相應的值,否則為print當前行 ( $0)。為了做到這一點,我采用了所謂的三元運算子條件?valueiftrue :valueiffalse
(在 GNU Awk 5.0.1 中測驗)
uj5u.com熱心網友回復:
注意perl標簽,這是一個 Perl 解決方案:
perl -ane 'if ($eof) {
if (exists $h{ $F[2] }) {
print $h{ $F[2] }
} else { print }
} else {
$h{ $F[2] } = $_;
$eof = 1 if eof;
}' -- file2 file1
-n逐行讀取輸入,運行每一行的代碼;-a將空格上的每一行拆分為 @F 陣列;- 我們在第一個檔案的末尾設定了變數$eof,即file2;
- 在讀取第一個檔案(file2)時,我們將每一行存盤到由第三列鍵控的哈希中;
- 在讀取第二個檔案(file1)時,我們檢查哈希是否包含第三列的行:如果是,我們列印它,否則我們列印當前行。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/450436.html
