2017-07-11 18 views
-2

我在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腳本

+0

請找文件的詳細信息file1中 2 B 3c的 文件2 b 22分配 一個11 C 33 輸出 1 AA 11 2 BB 22 3毫升33 –

+0

有一個特別的網站是:https://superuser.com/ – iehrlich

+0

此外,'男子1貼' – iehrlich

回答

1

使用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 

訂單將被第二個文件的順序。如果您希望按其他順序排序,請將file2awk ... file1 <(sort file2))或awk進程的輸出(awk ... | sort)分類。

+1

'貼'。它被稱爲'粘貼'。此外,它是[錘子的法則]的完美例子(https://en.wikipedia.org/wiki/Law_of_the_instrument):) – iehrlich

+0

@iehrlich是的,我知道。試圖生活的定義(專業和發燒友程序員的_問題和答案網站:)(順便說一句你的意思是'加入'?) –

+1

是的,誤解了一下:) – iehrlich

相關問題