2016-08-04 54 views
0

我看起來像這樣的兩個文件:如何從file1中提取行,基於它的/ file1(僅)的第一列與linux中的file2的匹配信息?

file 1: 
HO840F3000336240 HOUSAM129901651 HOUSAF132871174 F 20060607 Yes 
HO840F3000336251 HOUSAM129800008 HOUSAF135774690 F 20060718 Yes 
HO840F3000336254 HOUSAM129901651 HOUSAF135357862 F 20060724 Yes 
HO840F3000487279 HOUSAM131520543 HOUSAF135761935 F 20061226 Yes 
HOUSAM55967108 HOUSAM53557280 HOUSAF53557285 M 20091129 Yes 
HOUSAF55969445 HOUSAM55967108 HOUSAF53579684 F 20120103 Yes 

file 2: 
HO840F3000336251 
HO840F3000487279 
HOUSAF135761935 
HOUSAM55967108 

我想什麼做的是提取文件1,其中第一列是在文件2.因此,第一列共有的那些行,在此基礎上例如,輸出應該是:

file3: 

HO840F3000336251 HOUSAM129800008 HOUSAF135774690 F 20060718 Yes 
HO840F3000487279 HOUSAM131520543 HOUSAF135761935 F 20061226 Yes 
HOUSAM55967108 HOUSAM53557280 HOUSAF53557285 M 20091129 Yes 

有什麼建議嗎?

+1

可能是一個問題,最適合superuser.com或serverfault.com,但我們去:

排序基於第一列這兩個文件後'爲線\'貓文件2 \'; {grep $ line file1; }> file3' –

+0

好建議由保羅,但這種類型的問題的理想場所是http://unix.stackexchange.com/ –

+0

這[回答](http://stackoverflow.com/a/38400436/4082052)完美的作品...這個問題應該被標記爲重複我覺得 – Sundeep

回答

0

答案是使用連接命令,而不是grep的。

join File1 file2 > file3 
2

更新:

此命令將創建具有所需輸出的file3。測試和工程:

cat file1 | grep -f file2 > file3

輸出:

HO840F3000336251 HOUSAM129800008 HOUSAF135774690 F 20060718 Yes 
HO840F3000487279 HOUSAM131520543 HOUSAF135761935 F 20061226 Yes 

它使用-f開關中的grep這需要一個文件名,每行一個圖案。按man grep

-f FILE, --file=FILE 
Obtain patterns from FILE, one per line. The empty file contains zero patterns, 
and therefore enter code here`matches nothing. (-f is specified by POSIX.) 
相關問題