Sometimes you may need to merge two files in Linux. You can easily do this using cat command which is available in every Linux distribution. In fact, it allows you to create, view, append and combine files. In this article we will look at how to combine two files in Linux using cat command.
How to Combine Two Files in Linux
There are different ways to combine two files in Linux. We will look at each of these use cases one by one.
Let us say you have two files /home/file1.txt and /home/file2.txt that you want to combine.
1. Display combined data of two files
If you only want to display the contents of two files together without actually changing them or creating a new file, just run the following command, listing your file names one after the other, after cat command.
$ sudo cat /home/file1.txt /home/file2.txt
You will see the content of both files one below the other.
Similarly, you can display contents of multiple files, not just two, by listing their file paths one after the other, after cat command.
$ sudo /home/file1.txt /home/data/file2.txt /etc/data/file3.txt
Please note, if you do not specify the full file paths in above commands, cat command will look for those files in your present working directory.
2. Combine two files into a new file
Let us say you want to create a new file with the combined content of your two files. In this case, use > operator after the list of files you want to concatenate, followed by the file path of final file. Here is an example to combine two files file1.txt and file2.txt into new file file3.txt
$ sudo cat /home/file1.txt /home/file2.txt > /etc/data/file3.txt
In the above case, our two files file1.txt and file2.txt remain unchanged while the content of file3.txt is completely overwritten. If this final file file3.txt does not exist, Linux will automatically create it before storing the contents of file1.txt and file2.txt into it.
You can use the above command to combine any number of files. Just make sure you add > operator only after the names of all files you want to concatenate.
$ sudo cat /home/file1.txt /home/file2.txt /home/file3.txt /home/file4.txt> /etc/data/file3.txt
3. Append content to file
As mentioned above, when you use > operator, it completely overwrites the content of final file. If you only want to append to its existing content and not overwrite it, then use >> operator instead.
$ sudo cat /home/file1.txt /home/file2.txt >> /etc/data/file3.txt
In this case, the contents of file1.txt and file2.txt are appended to file3.txt. Similarly, you can append content of multiple files to a single file.
$ sudo cat /home/file1.txt /home/file2.txt /home/file3.txt /home/file4.txt >> /etc/data/file3.txt
In this article, we have looked at 3 different use cases to combine data of files using cat command. You may use it to only display the combined data, store combined data into a new file, or append data to an existing file.