How to Join Two Text Files in Linux

To join two or more text files on the Linux command-line, you can use the cat command. The cat (short for “concatenate”) command is one of the most commonly used commands in Linux as well as other UNIX-like operating systems, used to concatenate files and print on the standard output.

It is not only used to view files but can also be used to create files together with the redirection character.

View Contents of File in Linux

To view the contents of a file without opening it, you can use the cat command as shown (remember to replace domains.txt and domains2.txt with the names of the files you wish to combine):

[abhi@linuxshelltips:~]$ cat domains.txt
tecmint.com
cyberciti.biz
[abhi@linuxshelltips:~]$ cat domains2.txt 
linuxshelltips.com
google.com

Join Contents of Two Files in Linux

To join or combine the two files and view them as one on the terminal, run the following command:

[abhi@linuxshelltips:~]$ cat domains.txt domains2.txt
tecmint.com
cyberciti.biz
linuxshelltips.com
google.com

You can also join three or more files, for example:

[abhi@linuxshelltips:~]$ cat file1 file2 file3
OR
[abhi@linuxshelltips:~]$ cat file1 file2 file3 file4

After joining files, you can save the output in a single file using the redirection character like the following:

[abhi@linuxshelltips:~]$ cat domains.txt domains2.txt > domains_all.txt
[abhi@linuxshelltips:~]$ cat domains_all.txt

Also, you can join two or more files and append(add) their output to an existing file. For example:

[abhi@linuxshelltips:~]$ cat file1 file2  >> domains_all.txt

Merge Contents of Two Files Using Sed Command

Alternatively, you can also use the popular sed (a streamer editor) to join or merge the content of two or more files on the command-line, by using its r flag, which instructs sed to read the file provided as an argument. If there are many files, it reads all of them and displays their content as a combined output.

[abhi@linuxshelltips:~]$ sed r domains.txt domains2.txt
[abhi@linuxshelltips:~]$ sed r domains.txt domains2.txt > sed_out.txt
[abhi@linuxshelltips:~]$ cat  sed_out.txt

If you have any other questions about this topic, do not hesitate to ask for help in the comments section.

Got something to say? Join the discussion.