如何将应用程序的输出分成几个文件?

How to partition app's output into several files?

所以,我有一个应用程序。而且不是我写的。这是一个命令行应用程序。它输出一些我可以写入文件的字符串,如下所示:

anApp -input myFile.txt > myFileOutput.txt

问题是输出太大,计算机内存不足。是否可以这样做:

anApp -input myFile.txt > i=0; for each 100000 lines; touch newFile%d $(i++); $cat 100000lines >> newFile%d $(i++); done

因为是比较笨拙的伪代码,所以我也补充说明:

  1. 每 100000 行(例如)
  2. 创建一个名为:newFile# 的新文件 - 其中 # 是从 0 到 n 的数字
  3. 将这 100000 行写入新创建的文件。

我认为可能还有另一种选择 - 以现金形式保留 anApp 的产出。然而,文件很大,它包含一些结果,如果它会丢失......这不是我希望发生的事情。

一种选择是使用 split:

anApp -input myFile.txt | split -l 100000 - myFileOutput

这将生成名称如 myFileOutputaamyFileOutputab 等的文件

要更好地控制输出文件的名称,您可以使用 awk:

NR % 100000 == 1 { close(outfile); outfile = sprintf("myFileOutput%02d", i++) }
{ print > outfile }

您可以将该脚本保存到一个文件中,运行它就像:

anApp -input myFile.txt | awk -f script.awk