2011-05-06 137 views
3

我有這種格式比較兩個文件

file1= filename val1 val2 
file2= filename val3 val4 

我想比較的文件名和兩個文件,如果他們有相同的名字,我想第三個文件像這 -

filename val1 val2 val3 val4 

我正在從file1中挑選一個文件名,然後通過file2來查看我是否可以得到它。然後尋找指針返回file2的頂部爲下一個文件名..有一個更有效的方法來做到這一點?

+2

你可能想澄清你的問題,並顯示您正在使用的代碼。 – zeekay 2011-05-06 00:47:57

回答

2

創建詞典file2[filename] = (val3, val4)。你可以創建一次,然後查找時間爲你從file1得到的給定文件名需要一段時間(即或多或少獨立於文件2的大小)

4

這聽起來像你要找的是標準join命令(不是Python,而是一個標準的Unix shell實用程序)。下面是來自手冊頁剪斷的系統上(似乎有更多的細節比Linux的man page for join):

 join phonedir names 

     If the phonedir file contains the following names: 

     Adams A.  555-6235 
     Dickerson B. 555-1842 
     Erwin G.  555-1234 
     Jackson J.  555-0256 
     Lewis B.  555-3237 
     Norwood M.  555-5341 
     Smartt D.  555-1540 
     Wright M.  555-1234 
     Xandy G.  555-5015 

     and the names file contains these names and department numbers: 

     Erwin   Dept. 389 
     Frost   Dept. 217 
     Nicholson  Dept. 311 
     Norwood   Dept. 454 
     Wright   Dept. 520 
     Xandy   Dept. 999 

     the join command displays: 

     Erwin G.  555-1234  Dept. 389 
     Norwood M.  555-5341  Dept. 454 
     Wright M.  555-1234  Dept. 520 
     Xandy G.  555-5015  Dept. 999 
+0

謝謝!不幸的是我得到一個額外的新行..所以我得到的最終結果是文件名val1 val2(在新行)val3 val4。我希望它像你展示的那樣 - 沒有file1之後的換行符。我正在使用join file1 file2> outputfile – Illusionist 2011-05-06 01:43:05

+0

@Illusionist:它可能*與行結尾相關。您的文件可能是CRLF終止(DOS風格)? – 2011-05-06 01:47:50

+0

是的,它是CLRF終止 – Illusionist 2011-05-06 01:50:37