With the Bash shell in Linux it is quite simple to append the contents of one file to another, here we will cover how to perform file concatenation.
In this example we have two files, file1 and file2. Both files contain unique contents, and we want to join them both together without overwriting any of the data.
This can be done quite simply in bash and other shells by using ‘>>’ to append the contents with the ‘cat’ command, as shown below.
First we’ll create our example files.
[[email protected] ~]# echo "file1 contents" > file1 [[email protected] ~]# echo "file2 contents" > file2
Now we will concatenate these files together, by adding file2 to the bottom of file1.
[[email protected] ~]# cat file2 >> file1 [[email protected] ~]# cat file1 file1 contents file2 contents
The first line above uses ‘>>’ to append the contents of file2 to the end of file1 without overwriting anything. The second line is simply used to output the contents of file1, showing that we have successfully appended the content of file2 to file1.
It’s important that ‘>>’ is used, as this appends the content. If instead ‘>’ was used, file1 would be deleted and replaced entirely with the contents of file2.
We can also add the contents of file1 and file2 into a completely new file, file3.
cat file1 file2 >> file3
This way we don’t modify the original contents of either file1 or file2, and instead create a new file, file3, which contains the contents of both file1 and file2 joined together.
As file3 does not exist here, it is created. If the file specified does exist it will be created, however if the destination file does exist the contents are simply appended on to the end of that file.
As shown we can use the ‘cat’ command and the ‘>>’ operator to append one file to another without removing the original content.