2013-08-29 117 views
1

我试图将存储在CSV文件中的多个结果连接在一起,第一列作为索引。Linux - 将多个CSV文件合并为一个

问题是我有各种数量的文件,并且索引结果可能因文件而异,有些结果较少。

在Linux中,脚本化过程将所有文件合并到一个文件中最简单的方法是什么,空白字段为空结果?我遇到过Linux加入,粘贴和列没有运气。 Mybe我应该尝试使用另一种工具,或者Python或Perl?

数据文件是这样的:

文件1:

  header1 header2 header3 
result_A 10   11  12 
result_B 13   14  15 
result_C 16   17  18 
result_D 19   20  21 
result_E 22   23  24 
result_F 25   26  27 

文件2:

  header1 header2 header3 
result_B 40   41  42 
result_F 43   44  45 

文件3:

  header1 header2 header3 
result_C 60  61  62 
result_D 63  64  65 
result_F 66  67  68 

并希望的结果应该是这样的:

  file1 file1  file1 file2 file2  file2  file3 file3  file3 
      header1 header2 header3 header1 header2 header3  header1 header2 header3 
result_A 10  11  12               
result_B 13  14  15   40  41  42        
result_C 16  17  18          60  61  62 
result_D 19  20  21          63  64  65 
result_E 22  23  24               
result_F 25  26  27   43  44  45   66  67  68 

回答

1

UNIX join应该让你很长的路要走:

join -a 1 -e '0' "-t " -j 1 
    <(sort <(join -a 1 -e '0' "-t " -j 1 <(sort file1) <(sort file2))) 
    <(sort file3) 

(全部在同一行)。请注意0​​在引号内有TAB字符。输入^V<Tab>

如果你知道的输入进行排序,这将是更好地使用

join -a 1 -e '0' "-t " -j 1 
    <(join -a 1 -e '0' "-t " -j 1 file1 file2) 
    file3 

(全部在一行上)打印:

id  header1 header2 header3 header1 header2 header3 header1 header2 header3 
result_A  10  11  12 
result_B  13  14  15  40  41  42 
result_C  16  17  18  60  61  62 
result_D  19  20  21  63  64  65 
result_E  22  23  24 
result_F  25  26  27  43  44  45  66  67  68 

现在,你可以看到,在我的Cygwin系统-e '0'显然不能像广告一样工作。我建议在不同的系统上尝试这个,因为我不认为在标准UNIX实用程序中发现了这样一个重要的错误。

+0

非常感谢,对于提示键入TAB字符,我不知道这一点。 该命令快到了。我在我身边尝试过,结果相同:C和D行中的值60,61,62,63,64,65应该在第三列。 由于某些原因,如果缺少一行,它不会创建正确的值。 – zlig

+0

是的。它有点不错,但是它不会像'[join -e'的手册页](http://linux.die.net/man/1/join)中记录的那样'替换掉EMPTY输入字段' 。嗯。这可能是我犯的一个错误。 – sehe

+0

在shell中“键入”制表符的替代方法是使用printf格式的引用。这适用于bash,一些Almquist衍生物(即破折号)和其他可能的衍生物。使用Ctrl-v转义标签,而不是使用'$'\ t''。请注意,这种格式不希望生活在双引号内。你应该可以像'-t $'\ t''一样使用它。您可以在[QUOTING]下的bash手册页中找到更多信息(https://www.freebsd.org/cgi/man.cgi?query=bash#QUOTING)。我喜欢这种方法,因为它通过复制和粘贴来保持选项卡,这对于SO答案来说特别好。 :-) – ghoti