【问题标题】:Adding trec format tags to thousands of file将 trec 格式标签添加到数千个文件
【发布时间】:2011-03-15 11:37:21
【问题描述】:

我需要在目录中的数千个文件中添加文件文本等标签,我尝试使用 cat 并使用

将其输出到文件流
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

但是这样做很慢,请告诉我一个更好,更有效的方法来做到这一点。os不可能使用c来做。我们如何批量打开文件,然后处理它们并放回去,因为它可以加快这个过程因为我想打开和写入文件是瓶颈。

是否有预制程序(高效且快速)来完成这项工作,因为我们时间紧缺。

【问题讨论】:

  • 请不要cross-post。此外,如果您自己无法关联您的帐户,您应该让管理员关联您的帐户。

标签: c shell programming-languages operating-system copying


【解决方案1】:

这是一个快速的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()

我还没试过。

【讨论】:

    【解决方案2】:

    不要cat temp &gt; $file,只需mv temp $file——您不需要重写文件,只需重命名即可。这当然是导致性能不佳的原因之一

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

    您可能希望选择比“gau”、“gau_”和“gau1”更具描述性的文件名。

    【讨论】:

      猜你喜欢
      • 2021-07-31
      • 2020-03-29
      • 1970-01-01
      • 2012-05-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-23
      • 2013-12-11
      相关资源
      最近更新 更多