Linux join command
The Linux join command is used to join lines from two files that have matching content in the specified field.
It finds lines with matching content in the specified field from two files, merges them, and outputs the result to standard output.
Syntax
join [-i][-a<1或2>][-e<字符串>][-o<格式>][-t<字符>][-v<1或2>][-1<栏位>][-2<栏位>][--help][--version][文件1][文件2]
Parameters:
- -a<1 or 2> In addition to the original output, also display lines from the command file that have no matching field.
- -e
If the specified field is not found in [File 1] and [File 2], fill the output with the string from the option. - -i or --igore-case ignores differences in case when comparing field content.
- -o
Display the result in the specified format. - -t
Use the specified character as the field separator. - -v<1 or 2> Same as -a, but only display lines from the file that have no matching field.
- -1
Join on the specified field of [File 1]. - -2
Join on the specified field of [File 2]. - --help Display help.
- --version Display version information.
Example
Join two files.
To understand the join command clearly, first use the cat command to display the contents of the files testfile_1 and testfile_2.
Then compare the two files in the default way, joining lines whose specified fields have matching content; enter the command in the terminal:
join testfile_1 testfile_2
First, view the file contents in testfile_1 and testfile_2:
$ cat testfile_1 #testfile_1文件中的内容
Hello 95 #例如,本例中第一列为姓名,第二列为数额
Linux 85
test 30
cmd@hdd-desktop:~$ cat testfile_2 #testfile_2文件中的内容
Hello 2005 #例如,本例中第一列为姓名,第二列为年份
Linux 2009
test 2006
Then use the join command to join the two files; the result is as follows:
$ join testfile_1 testfile_2 #连接testfile_1、testfile_2中的内容
Hello 95 2005 #连接后显示的内容
Linux 85 2009
test 30 2006
The positions of File 1 and File 2 affect the result written to standard output. For example, swap the two files in the command, that is, enter the following command:
join testfile_2 testfile_1
The final output on standard output will change, as shown below:
$ join testfile_2 testfile_1 #改变文件顺序连接两个文件
Hello 2005 95 #连接后显示的内容
Linux 2009 85
test 2006 30
Linux Command Reference