【问题标题】:How to merge multiple files into single file in given directories如何将多个文件合并为给定目录中的单个文件
【发布时间】:2015-08-13 22:10:12
【问题描述】:

我想编写一个 shell 脚本来合并给定目录中多个文件的内容。

DIR1 contains sample1.txt sample2.txt
    sample1.txt contents  :---this is sample1 file
    sample2.txt contents  :---this is sample2 file

DIR2 contains demo1.txt demo2.txt
    demo1.txt contents  :---this is demo1 file

我试过了:

(find /home/DIR1  /home/DIR2 -type f | xargs -i cat {} ) > /result/final.txt

成功了!

this is sample2 file  this is sample1 file  this is demo1 file

但是输出出现在一行中,我需要将每个文件的输出放在单独的新行中。 像这样:

this is sample1 file
this is sample2 file  
this is demo1 file

如何做到这一点?

如有任何帮助,我们将不胜感激。

【问题讨论】:

  • 我无法重现您的问题。您的示例在我的机器上运行良好。我不知道为什么在你的情况下输出打包成单行。
  • @mainframer 在他的情况下它的工作方式不同,因为原始文件不以换行符结尾

标签: shell cat xargs


【解决方案1】:

正如 cmets 中所指出的,问题可能是因为文件结尾 (EOF) 前面没有 \n(换行符)。

规避此问题的一种方法是将“---”替换为换行符。希望以下命令可以解决问题:

(find DIR1/  DIR2/ -type f | xargs -i cat {} ) | sed "s/$/\r/g" > result/final.txt

【讨论】:

  • 不,实际上它只是一个示例代码,但是真正的文件最后没有“--”......那么如何为任何类型的数据修复它?
  • @ashwini,问题在于行尾。 $ 符号表示该行的结束。我已经相应地编辑了答案。
  • 没有错误但输出出现在一行中
【解决方案2】:

您的文件不以换行符结尾,因此输出文件中没有换行符。

您应该确保您的输入文件以换行符结尾,或者在find 命令中添加它们:

find /home/DIR1  /home/DIR2 -type f -exec cat {} \; -exec echo \;

【讨论】:

  • 它有效,但我想将输出保存在文件中,而不是在终端上...我应该在 cmd 中添加什么?
  • 是的,我用过 find ....... -exec echo \; > /result/final.txt 它有效,但它是正确的方法吗?
  • 上面的脚本在两个文件的内容之间添加了空行如何删除?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-06-23
  • 2019-03-14
  • 1970-01-01
  • 2011-06-02
  • 2015-08-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多