我在unix環境下2個文件需要兩列從比較兩個文件,並使用寫入所有列到新的文件UNIX
文件1:
1 a
2 b
3 c
文件2:
----------
## Heading ##
2 bb
1 aa
3 cc
如何得到輸出文件
輸出:
1 a 1 aa
2 b 2 bb
3 c 3 cc
使用unix shell腳本
我在unix環境下2個文件需要兩列從比較兩個文件,並使用寫入所有列到新的文件UNIX
文件1:
1 a
2 b
3 c
文件2:
----------
## Heading ##
2 bb
1 aa
3 cc
如何得到輸出文件
輸出:
1 a 1 aa
2 b 2 bb
3 c 3 cc
使用unix shell腳本
使用awk。這是一個awk經典:
$ awk 'NR==FNR{a[$1]=$0;next}$1 in a{print a[$1],$0}' file1 file2
2 b 2 bb
1 a 1 aa
3 c 3 cc
解釋:
$ awk '
NR==FNR { # process first file
a[$1]=$0 # hash record, use first field as hash key
next # move to next record
}
$1 in a { # second file, if key found in the hash
print a[$1],$0 # output it from the hash along with the current record
}' file1 file2 # mind the order
訂單將被第二個文件的順序。如果您希望按其他順序排序,請將file2
(awk ... file1 <(sort file2)
)或awk進程的輸出(awk ... | sort
)分類。
請找文件的詳細信息file1中 2 B 3c的 文件2 b 22分配 一個11 C 33 輸出 1 AA 11 2 BB 22 3毫升33 –
有一個特別的網站是:https://superuser.com/ – iehrlich
此外,'男子1貼' – iehrlich