Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/unix/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Unix:基于公共列使用多个值联接多个列?_Unix_Join_Sh - Fatal编程技术网

Unix:基于公共列使用多个值联接多个列?

Unix:基于公共列使用多个值联接多个列?,unix,join,sh,Unix,Join,Sh,所以我有两个以制表符分隔的文件,其中有两列,我需要根据公共列中的值来连接它们。问题是公共列中的某些值与第二列中的不同值重复。。。例如: File 1: A 3456 B 234 A 4509 A 576 C 122 B 235 File 2: A 48556 A 49 B 9694 C 84 C 96 Desired Output: A 3456 4509 576 48556 49 B 234 235 9694 C 122 8

所以我有两个以制表符分隔的文件,其中有两列,我需要根据公共列中的值来连接它们。问题是公共列中的某些值与第二列中的不同值重复。。。例如:

File 1:  
A 3456  
B 234  
A 4509  
A 576  
C 122  
B 235  


File 2:  
A 48556  
A 49  
B 9694  
C 84  
C 96  

Desired Output:  
A 3456 4509 576 48556 49  
B 234 235 9694  
C 122 84 96  

我正在尝试在Unix中编写一个“简单”的脚本,可以做到这一点,老实说,我甚至不知道从哪里开始。

下面是一个连接两个文件的awk方法:-

awk '
        {
                I[$1]
                A[$1 FS $2]
        }
        END {
                for ( k in I )
                {
                        printf "%s ", k
                        for ( j in A )
                        {
                                split( j, T )
                                if ( T[1] == k )
                                        printf "%d ", T[2]
                        }
                        printf "\n"
                }
        }
' file1 file2

仅供参考,你的问题有点误导。您不希望在公共列上进行联接。您希望列出共享一个公共密钥的N个文件中的所有不同值。在SQL术语中,这更像是有时所谓的“折叠”

以下是一种接近指定输出的方法:

$ sort -u -k1  d1 d2 | 
  awk '$1 != prev { if (line) {print line}; prev = $1; line = $0; next;} 
       {line = line " " $2} 
       END{ print line }' 
A 3456 4509 48556 49 576
B 234 235 9694
C 122 84 96
另一个awk:

$ awk '{a[$1]=a[$1] OFS $2}END{for(i in a)print i a[i]}' file1 file2 #...
输出为awk默认顺序:

A 3456 4509 576 48556 49
B 234 235 9694
C 122 84 96
解释:

$ awk '{
    a[$1]=a[$1] OFS $2   # group by 1st field value by hashing to an array, 
}                        # append 2nd field values to it
END {                    # after processing the data records
    for(i in a)          # iterate all array elements 
        print i a[i]     # print key and value
}' file1 file2           # all the files you want to process

请单击提供的标记进行标记,并首先阅读其标记wiki。JOIN是表操作符的一个类别&不仅仅意味着“combine”。(您需要联合的某个聚合。)