Objective: Concatenate or append multiple text or binary files into a single file on Unix / Linux.
If you have two files, foo1.txt
and foo2.txt
and if you want to concatenate the two files into foo.txt
, you can use the cat
command.
1 |
$ cat foo1.txt foo2.txt > foo.txt |
The above command works for both text and binary files. The foo.txt
will contain the contents of the foo1.txt
file followed by the contents of the foo2.txt
file. If you want to change the order of the contents, you will need to change the cat
file list argument.
If you would like to append the contents of foo2.txt
to the end of foo1.txt
, you can use the following syntax.
1 |
$ cat foo2.txt >> foo1.txt |
Note the use of >>
for redirection. Redirection using a single >
will truncate the foo1.txt
file to zero-length and copy the contents of foo2.txt
file. Use >>
when appending files.
If you have a lot of .txt
files and if you want to merge all of them together into a single file, you can use the following command syntax.
1 |
$ cat *.txt > footxt.out |
All .txt
file contents will be written to an output file called footxt.out
.
If you would like to concatenate a single file to itself multiple times, you can use a for
loop. To copy the contents of foo1.txt
file multiple times, let’s say 10 times, and write the output to foo.txt
, we can use the following loop.
1 |
$ for i in {1..10}; do cat foo1.txt >>foo.txt; done |