我想复制五个文件的内容到一个文件。我试着对每个文件使用cp。但是这会覆盖从上一个文件复制的内容。我也试过

paste -d "\n" 1.txt 0.txt

但这并没有奏效。

我希望我的脚本在每个文本文件的末尾添加换行符。

如。文件1.txt, 2.txt, 3.txt。把1,2,3的内容放在0.txt中

我该怎么做?


当前回答

If the original file contains non-printable characters, they will be lost when using the cat command. Using 'cat -v', the non-printables will be converted to visible character strings, but the output file would still not contain the actual non-printables characters in the original file. With a small number of files, an alternative might be to open the first file in an editor (e.g. vim) that handles non-printing characters. Then maneuver to the bottom of the file and enter ":r second_file_name". That will pull in the second file, including non-printing characters. The same could be done for additional files. When all files have been read in, enter ":w". The end result is that the first file will now contain what it did originally, plus the content of the files that were read in.

其他回答

如果您有一个特定的输出类型,那么执行如下操作

cat /path/to/files/*.txt >> finalout.txt

您需要cat (concatenate的缩写)命令,并将shell重定向(>)导入到输出文件

cat 1.txt 2.txt 3.txt > 0.txt

所有的(文本)文件到一个

find . | xargs cat > outfile

Xargs生成find的输出行。猫的论点。

Find有很多选项,比如name '*.txt'或type。

如果您想在管道中使用它,您应该查看它们

另一个选项是sed:

sed r 1.txt 2.txt 3.txt > merge.txt 

还是……

sed h 1.txt 2.txt 3.txt > merge.txt 

还是……

sed -n p 1.txt 2.txt 3.txt > merge.txt # -n is mandatory here

或者没有定向……

sed wmerge.txt 1.txt 2.txt 3.txt

注意最后一行也写入merge.txt(不是wmerge.txt!)。您可以使用w"merge.txt"来避免与文件名混淆,使用-n表示静默输出。

当然,您也可以使用通配符来缩短文件列表。例如,对于上面例子中有编号的文件,你可以这样用花括号指定范围:

sed -n w"merge.txt" {1..3}.txt
for i in {1..3}; do cat "$i.txt" >> 0.txt; done

我找到这个页面是因为我需要将952个文件合并为一个。我发现如果你有很多文件,这个工作得更好。这将为您需要的任意数量的数字进行循环,并使用>>将每个数字附加到0.txt的末尾。

编辑:

正如评论中提到的:

cat {1..3}.txt >> 0.txt

or

cat {0..3}.txt >> all.txt