2013-01-07 91 views
4

我需要使用file1中第1列($ 1)中的字符串找到与file1.txt中第1列($ 1)中的字符串匹配的文件。文本。然后我想加入新文件中匹配的行。匹配两个文件的第一列中的值并将匹配的行加入到一个新文件中

cat file1.txt 
1050008 5.156725968 8.404038296 124.9198605 3.23E-21 2.33E-17 38.57865782 
3310747 5.631470026 8.581936875 124.6039122 3.34E-21 2.33E-17 38.55204806 
5910451 4.900364671 8.455329195 124.5720603 3.35E-21 2.33E-17 38.54935989 
730156 5.565210738 8.48792701 122.2168789 4.28E-21 2.33E-17 38.34773989 

cat file2.txt 
4230037 ILMN Controls ILMN_Controls ERCC-00071 ILMN_333646 ERCC-00071 ERCC-00071 
1050008 ILMN Controls ILMN_Controls ERCC-00009 ILMN_333584 ERCC-00009 ERCC-00009 
5260356 ILMN Controls ILMN_Controls ERCC-00053 ILMN_333628 ERCC-00053 ERCC-00053 
3310747 ILMN Controls ILMN_Controls ERCC-00144 ILMN_333719 ERCC-00144 ERCC-00144 
5910451 ILMN Controls ILMN_Controls ERCC-00003 ILMN_333578 ERCC-00003 ERCC-00003 
1710435 ILMN Controls ILMN_Controls ERCC-00138 ILMN_333713 ERCC-00138 ERCC-00138 
1400612 ILMN Controls ILMN_Controls ERCC-00084 ILMN_333659 ERCC-00084 ERCC-00084 
730156 ILMN Controls ILMN_Controls ERCC-00017 ILMN_333592 ERCC-00017 ERCC-00017 

我想输出文件看起来像这样:

out.txt 
1050008 5.156725968 8.404038296 124.9198605 3.23E-21 2.33E-17 38.57865782 1050008 ILMN Controls ILMN_Controls ERCC-00009 ILMN_333584 ERCC-00009 ERCC-00009 
3310747 5.631470026 8.581936875 124.6039122 3.34E-21 2.33E-17 38.55204806 3310747 ILMN Controls ILMN_Controls ERCC-00144 ILMN_333719 ERCC-00144 ERCC-00144 
5910451 4.900364671 8.455329195 124.5720603 3.35E-21 2.33E-17 38.54935989 5910451 ILMN Controls ILMN_Controls ERCC-00003 ILMN_333578 ERCC-00003 ERCC-00003 
730156 5.565210738 8.48792701 122.2168789 4.28E-21 2.33E-17 38.34773989 730156 ILMN Controls ILMN_Controls ERCC-00017 ILMN_333592 ERCC-00017 ERCC-00017 

的文件是制表符分隔,并有一些列的缺失值。

有一个在FILE2.TXT 31列> 47000线,我想如果你有一个解决方案,这样做在bash(OSX)

我将不胜感激,如果你能简要explainn的步骤我对此很陌生。

+0

检查这里:HTTP://theunixshell.blogspot.com /2012/12/file-comparisons-using-awk-match-columns.html或这里:http://theunixshell.blogspot.com/2012/12/awk-one-liner-for-multi-column.html – Vijay

回答

10
awk 'BEGIN { 
    FS = OFS = "\t" 
    } 
NR == FNR { 
    # while reading the 1st file 
    # store its records in the array f 
    f[$1] = $0 
    next 
    } 
$1 in f { 
    # when match is found 
    # print all values 
    print f[$1], $0 
    }' file1 file2 
+1

+ 1清晰的结构化代码和漂亮的评论 – Kent

+3

+1为一个不错的脚本。如果在任一文件的第一列中出现空格,则会失败,或者在某行中缺少该字段,并且OP会特别说明某些字段缺少值,因此您应该真正使用'awk'BEGIN {FS = OFS =“\ t”} ...''是安全的。 –

+0

@EdMorton,更正了,谢谢! –

8

如果你不介意的输出由第一列被排序,那么你可以使用这个调用的join命令:

join <(sort file1.txt) <(sort file2.txt) >out.txt 
+0

不错,优雅! –

+0

这是工作的正确工具! –

+0

这是一个不错的解决方案。有一种简单的方法来处理一些文件丢失行的情况吗? –

相关问题