Join lines of two files

The join command joins lines of two files on a common field. By default, fields are separated by spaces, although you can specify some other character by using the -t option.

Here is an example that will help you understand how this command works. Let’s say that we have two files: first_names.txt and last_names.txt:

linux example files

We can use the join command to join these two files:

linux join command

In the example above you can see that the join command used the first field (the numbers) as the one to match across files. Because the numbers were the same and in the first field in both files, the join command finished successfully.

You can specify another field to be used for the join operation. Let’s say that we have these two files:

linux example files 2

You can see the problem here: the first field is not the same in both files and the fields are separated with the / character instead of spaces. We need to do two things:

  • join the files by specifying the third field in the first file and the second field in the second file
  • define the character / as a field delimiter

We can specify another field by using the -1 and -2 option. -1 specifies the join field for the first file, and -2 for the second file. To define the character / as a delimiter, we need to use the -t option. Here is the command:

linux join by another field and delimiter

Subscribe to our Newsletter

Like us on Facebook

top
Geek University 2019