Skip to main content
Quick Tip

Merge Files in the Linux Command Line

Learn various ways of merging multiple files into another file in the Linux command line.

Sagar Sharma

Warp Terminal

Got two or more files and need to merge them in a single file? The simplest way would be to use the cat command. After all, the cat command's original purpose is to concatenate files.

Use the cat command to merge files in Linux

Merging two files is simple. You just have to append the filename to the cat command and that's it:

cat file_1 file_2 

As you can see, I used the cat command to show the contents of a file and then merged them.

But it won't save any changes. To save those changes, you have to redirect the file contents to another file.

cat file1 file2 > file3

Remember, the > will override the contents of the file so I would recommend using a new file as the cat will create the file if it doesn't exist.

So how can you modify the editing file while keeping the previous content intact?

Append changes to the existing file

To modify the existing file, you just have to use >> instead of single > and you'd be good to go.

cat file1 file2 >> file3

For example, I will make edit the existing file File_3.txt by appending Hello.txt and Sagar.txt:

As you can see, it added new text in the end line while keeping the old content intact.

Automate the merging files using the loop in Linux

Here, I will be using for loop (till three iterations as I want to merge three files) also you can use > or >> as per your needs.

for i in {1..3}; do cat "File_$i.txt" >> NewFile.txt; done

Use the sed command to merge files in Linux (temporary)

There are many times when you want to apply changes only for a specific time and in those cases, you can use sed.

Being a non-interactive way of editing files, the sed utility can be tremendously useful when used in the right way.

And when used with the h flag, it will hold the buffer temporarily:

sed h file1 file2 > file3

Wrapping Up

This was my take on how you can merge files using the sed and cat command. And if you have any queries, leave us a comment.

Sagar Sharma