2011-03-15 78 views
0

的我需要添加類似文件的文本標籤文件千元的目錄,我使用的貓和使用添加TREC的標記格式,成千上萬的文件

for file in * 
do 
cat ../gau > temp; //gau contain format i need to append in each file 
echo $file >>temp; 
cat ../gau_ >>temp ;//contains </DOCID> 
cat $file >>temp; 
cat ../gau1 >> temp; //this contain last sentence </DOC> 
cat temp > $file 
done 

它outputing到文件的流也試過,但這樣做是非常緩慢的可以請告訴我一個更好和有效的方法來做到這一點。可能做到使用c .how可以我們批量打開文件,然後處理它們並放回,因爲它可以固定此過程自打開和寫入文件是瓶頸我想。

有沒有和預製的程序(這是高效和快速)做這項工作,因爲我們是在時間稀缺。

+0

請不要[cross-post](http://superuser.com/questions/257825/adding-trec-format-tags-to-thousands-of-file)。此外,如果您無法自行完成,則應請管理員鏈接您的帳戶。 – 2011-03-15 16:19:41

回答

0

這是一個快速的Python代碼,試試吧,它會執行比你的批處理腳本更快:

import os 

for dirname, dirnames, filenames in os.walk('/MY_DIRECTORY/'): 
    for filename in filenames: 
     with open(os.path.join(dirname, filename), "r+") as f: 
      str = f.read() # read everything in the file 
      f.seek(0) # rewind 
      f.write("Prepended text tags" + str) # write the new line before 
      f.close() 

我還沒有嘗試過,但。

0

不要cat temp > $file,只是mv temp $file - 你不需要重寫該文件,只需重命名它。這肯定的糟糕表現的原因之一

for file in *; do 
    { cat ../gau; echo $file; cat ../gau_ $file ../gau1; } > temp 
    mv temp $file 
done 

你可能想選擇除「GAU」,「gau_」和「gau1」更desctiptive文件名。

相關問題