Coder Perfect

How can I combine the contents of several files into a single file?

Problem

I’d want to replicate the contents of five folders into a single file in their current state. For each file, I attempted to do it with cp. However, this overwrites the contents of the previously copied file. I also made an attempt.

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

and it was a failure.

I’d like my script to conclude each text file with a newline.

Files 1.txt, 2.txt, and 3.txt, for example. In 0.txt, paste the contents of 1,2,3.

How do I go about doing it?

Asked by Steam

Solution #1

The cat (short for concatenate) command is required, along with shell redirection (>) into your output file.

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

Answered by radical7

Solution #2

For those of you who, like me, came into this post by accident, another method is to use find -exec:

find . -type f -name '*.txt' -exec cat {} + >> output.file

I needed a more powerful tool that would search many subdirectories in my instance, so I went with find. Taking it apart:

find .

Within the current working directory, take a look.

-type f

Only interested in files, not directories, etc.

-name '*.txt'

Reduce the number of results by naming them.

-exec cat {} +

For each result, run the cat command. “+” indicates that only one cat is generated (thanks @gniourf gniourf).

 >> output.file

Append the cat-ed contents to the end of an output file, as stated in earlier replies.

Answered by mopo922

Solution #3

Do something like this if you have a certain output type.

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

Answered by Eswar Yaganti

Solution #4

You may simply accomplish this if all of your files are in a single directory.

> 0.txt cat *

The files 1.txt, 2.txt, and so on will be placed in 0.txt.

Answered by Pooja

Solution #5

If all of your files have the same name, you may simply do:

cat *.log >> output.log

Answered by AeaRy

Post is based on https://stackoverflow.com/questions/18006581/how-to-append-contents-of-multiple-files-into-one-file