---
title: "How to implement full join on two files"
author: "jianpx"
date: "2012-08-28T08:33:21Z"
tags: ["JOIN", "Linux", "full join", "shell"]
categories: ["编程语言"]
slug: "how-to-implement-full-join-on-two-files"
draft: false
lastmod: "2012-08-28T08:33:21Z"
id: 1664554
url: "https://jianpx.iteye.com/blog/1664554"
---

5.1 使用场景： 如果需要对2个文件的数据实现像数据库里面的全连接一样的操作就可以用以下经验、命令实现。 这里的全连接是指对2个文件的数据按照某一列  
来做并集的操作，也就是两个文件会指定一个公有的列（当然这个列的数据可以有相同也可以有不同），然后求这个列的并集以及能同时输出其他列的值。如果某个文件的某一列  
（公有列除外）不存在于另一个文件的这一列，那么我们就要变量替换掉这个“不存在”的值。就像数据库会帮你替换成NULL值一样。

5.2 上代码例子！  
\[jianpx@jianpxs-MacBook-Pro ~/temp/test/join]$ cat a  
a,1  
b,2  
c,3  
d,4  
\[jianpx@jianpxs-MacBook-Pro ~/temp/test/join]$ cat b  
c,7  
d,9  
e,10

a、b两个文件我默认已经按照第一列排好序了（我们利用join命令时必须保证两个文件是按照某一个公有的列有序的！）  
然后我的需求是要输出类似这样的：  
a,1,NULL  
b,2,NULL  
c,3,7  
d,4,9  
e,NULL,10

从结果可以分析看看， 因为e开头的这一行不存在与a文件，所以连接的时候对应第二列的位置就应该被置为NULL（当然你也可以用其他默认值代替NULL，比数据库要灵活一点）  
而a开头的这一样也不存在于b文件，所以第三列的位置也应该是NULL。

从 man join得到的参数来看， -a 、-e、-o都能帮到我。  
\-a field\_number ： In addition to the default output, produce a line for each unpairable line in file file\_number. 意思是把两个文件中不匹配的行也输出出来。  
\-e string: Replace empty output fields with string 意思是指定需要变量替换的值。  
\-o list: The -o option specifies the fields that will be output from each file for each line with matching join fields.  Each element of list has the either the  
            form \`file\_number.field', where file\_number is a file number and field is a field number, or the form \`0' (zero), representing the join field.  The ele-  
            ments of list must be either comma (\`,') or whitespace separated.  (The latter requires quoting to protect it from the shell, or, a simpler approach is  
            to use multiple -o options.)   其实这里对我最有用的就是0可以代表公有的列的位置，这样就不用用一个明确的位置（比如1）来指定这个公共列了，因为  
用明确位置指定的缺点是这个公有列如果在两个文件上的位置是不一样就会有被替换的可能，比如在文件a是第一列，在文件2是第二列。

不知道大家现在能才出来没？（可以先不看下面的答案自己思考下）  
好， 公布答案了， 看看你们做的对不对。

\[jianpx@jianpxs-MacBook-Pro ~/temp/test/join]$ join -t, -j1 -o 0,1.2,2.2 -e NULL -a 1 -a 2 a b  
a,1,NULL  
b,2,NULL  
c,3,7  
d,4,9  
e,NULL,10