如何将多个文件合并到给定目录中的单个文件中

时间:2015-05-31 11:16:29

标签: shell cat xargs

我想编写一个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

如何实现这个目标?

任何帮助都会提前得到赞赏。

2 个答案:

答案 0 :(得分:0)

正如评论中指出的那样,问题可能是因为文件结尾(EOF)前面没有\ n(newLine字符)。

绕过这个问题的一种方法是用换行符替换“---”。希望以下命令解决问题:

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

答案 1 :(得分:0)

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

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

find /home/DIR1  /home/DIR2 -type f -exec cat {} \; -exec echo \;
相关问题