Unix / Linux: Concatenate Multiple Files

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.

$ 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.

$ 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.

$ 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.

$ for i in {1..10}; do cat foo1.txt >>foo.txt; done

Ibrahim is a technology enthusiast with a keen interest in *NIX (Unix, Linux) systems, Android, open source and other tech related stuff. When his cpu load is low, you can probably find him online playing on his Xbox or PlayStation.