Nov 28, 2022 2 min read

Merge Files in the Linux Command Line

Table of Contents

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 
merging two files using cat command in linux

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
merge two files using cat command in linux

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:

merge into existing file using cat command

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
using for loop to merge files in linux

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
use sed command to merge files

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
A software engineer who loves to tinker with hardware till it gets crashed. While reviving my crashed system, you can find me reading literature, manga, or watering my plants.
Great! You’ve successfully signed up.
Welcome back! You've successfully signed in.
You've successfully subscribed to Linux Handbook.
Your link has expired.
Success! Check your email for magic link to sign-in.
Success! Your billing info has been updated.
Your billing was not updated.