2014-07-16 61 views
0

我有两列文件。我需要打印第二个文件的内容如果第一个第二个这两个文件的列是相等的。例如:按两列匹配比较两个文件

file1 

Name1 123 blabla 
Name1 456 bla 
Name3 777 s 

file2 

Name1 123 something more 
Name2 456 some words 
Name4 111 no 

Desired output: 

Name1 123 something more 

我写了这个代码,但它仅适用于一列(第二次在这种情况下):

awk 'BEGIN{FS=OFS="\t"} NR == FNR {f[$2]; next;} $2 in f{print $0;}' file1 file2 

我发现这里的东西有关:comparing two columns in two files,但我无法找到正确的方法。我试过,但没有工作..:提前

awk 'BEGIN{FS=OFS="\t"} NR == FNR {f[$1 FS $2]; next;} if($1 in f && $2 in f){print $0;}' 

感谢,

回答

0

你可以有

awk 'NR == FNR { a[$1, $2]++; next } a[$1, $2]' file1 file2 

输出:

Name1 123 something more 
  • [$1, $2]不同于[$1 "," $2]。不知何故,Awk的实现可以确保$1, $2不会匹配文字字符串。
+0

它很好。谢谢。一个小问题,只有好奇心,你知道我的代码为什么不起作用吗? – cucurbit

+0

对于第二次尝试,您没有为'f [$ 1 FS $ 2]'赋值。而且你分别用这两个值'in's'f'中的$ 1和f'中的$ 2。当然,从来没有'f [$ 1]'和'f [$ 2]'。在你的版本中,如果(f $中有$ 1 FS $ 2),那么它可能是'f [$ FS $ 2] ++'...' – konsolebox