![如何在 awk/shell 中逐行合併具有相同記錄的 2 個檔案?](https://rvso.com/image/168793/%E5%A6%82%E4%BD%95%E5%9C%A8%20awk%2Fshell%20%E4%B8%AD%E9%80%90%E8%A1%8C%E5%90%88%E4%BD%B5%E5%85%B7%E6%9C%89%E7%9B%B8%E5%90%8C%E8%A8%98%E9%8C%84%E7%9A%84%202%20%E5%80%8B%E6%AA%94%E6%A1%88%EF%BC%9F.png)
我是 awk 和 shell 的新手,想知道如何使用 shell/awk 將 2 個檔案與具有相同記錄的行合併? file1 和 file2 的名稱順序可能不同。我只想合併具有相同記錄的行。請幫忙。
file1.txt
Mary 68
Tom 50
Jason 45
Lu 66
file2.txt
Jason 37
Tom 26
Mary 74
Tina 80
mergefile.txt
Marry 68 74
Tom 50 26
Jason 45 37
我嘗試了 awk,但運行腳本需要一些時間。想知道是否有更快速、更簡單的工具。
cat file1.txt | while read line
do
score1=$( echo $line | awk '{print $2}');
name1=$( echo $line | awk '{print $1}');
cat file2.txt | while read l
do
score2=$( echo $l | awk '{print $2}');
name2=$( echo $l | awk '{print $1}');
if [[ $name1 == $name2 ]]
then
echo "$name1 $score1 $score2" >> mergefile
break
fi
done
done
答案1
如果你想使用 awk:
$ awk 'NR==FNR {a[$1] = $2; next} $1 in a {print $1, $2, a[$1]}' file2.txt file1.txt
Mary 68 74
Tom 50 26
Jason 45 37
不需要排序,輸出將按照給定的第二個文件的順序排列。
解釋:
NR==FNR
是從第一個命名檔案中選擇記錄的規範方法{a[$1] = $2; next}
使用第一個欄位中的鍵和第二個欄位中的值填入數組$1 in a
如果第一個欄位已在第一個文件中看到;然後{print $1, $2, a[$1]}
列印第二個文件中的鍵和值以及第一個文件中的值
答案2
這聽起來像是一份工作join
,關聯式資料庫運算符
join <(sort file1.txt) <(sort file2.txt)
測試
$ cat file1.txt
Mary 68
Tom 50
Jason 45
Lu 66
$ cat file2.txt
Jason 37
Tom 26
Mary 74
Tina 80
$ join <(sort file1.txt) <(sort file2.txt)
Jason 45 37
Mary 68 74
Tom 50 26
join
是 POSIX 中指定的標準工具。
手冊join
頁指出:
The files file1 and file2 shall be ordered in the collating sequence of sort -b on the fields on which they shall be joined, by default the first in each line. All selected output shall be written in the same collating sequence.