Combine lines in two different files using the JOIN command in Linux

Home > Search > Linux commands

The join command will join lines in two different files. The join command will only combine lines that contain an identical first word or string. For example, let's say file1.txt contains "Hello World" and file2.txt contains "How are you today?" When attempting to join file1.txt and file2.txt, no output will be displayed, because the join command will only join lines in a file that begin with the same word or string.

~]# join file1.txt file2.txt


On the other hand, if file1.txt contains "Hello John" and file2.txt contains "Hello Susan", the join command will join these lines. The join command will only display the first word or string once.

~]# join file1.txt file2.txt
Hello John Susan


Not sorted

The lines in the files being joined must be sorted. If the files are not sorted, "not sorted" will be displayed when attempting to join the files. 

~]# join file1.txt file2.txt
join: file1.txt is not sorted


Use the sort command to sort the files being joined.

~]# sort file1.txt -o file1.txt
~]# sort file2.txt -o file2.txt
~]# join file1.txt file2.txt
Hello John Susan
Hello Frank Dawn


Add a Comment

We will never share your name or email with anyone. Enter your email if you would like to be notified when we respond to your comment.

Please enter in the box below so that we can be sure you are a human.