2014-09-10 66 views
-1

我需要找到在Unix的两个文件之间的差异之间的公共列位置,查找文件

文件1:

1,column1 
2,column2 
3,column3 

文件2:

1,column1 
2,column3 
3,column5 

我需要从文件1中找到文件2中公共列的位置 如果没有匹配的公司在file1中应该返回一些默认的索引值和列名。

输出:

1,column1 
    3,column3 
    -1,column5 

谁能帮我在Unix的脚本得到什么?

谢谢, 威廉指标

+1

听到['diff'](http://man.cx/diff)或['comm'](http://man.cx/comm)? – anishsane 2014-09-10 09:37:57

+0

为什么“file2-file1”包含“1,column1”? – anishsane 2014-09-10 09:39:55

+0

对不起,这不是差异,我必须找到共同的列位置并写入另一个文件。 – 2014-09-10 09:45:03

回答

1

AWK:

awk -F, 'NR==FNR{a[$2]=1; next;} ($2 in a)' file2 file1 

的grep +进程替换:

grep -f <(cut -d, -f2 file2) file1 

EDIT用于更新问题:

AWK:

awk -F, 'NR==FNR{a[$2]=$1;next} {if ($2 in a) print a[$2]","$2; else print "-1," $2}' file1 file2 
# if match found in file1, print the index, else print -1 
# (Also note that the input file order is reversed in this command, compared to earlier awk.) 

的grep:

cp file1 tmpfile #get original file 
grep -f <(cut -d, -f2 file1) -v f2 | sed 's/.*,/-1,/' >> tmpfile #append missing entries 
grep -f <(cut -d, -f2 file2) tmpfile # grep in this tmpfile 
+0

谢谢非常多,但小的帮助在文件2(这不匹配在文件1中)3,第5列这种情况下,我们如何可以指示-1,列5在输出文件。 – 2014-09-10 09:55:26

+1

用示例编辑你的问题。 – anishsane 2014-09-10 09:56:25

+0

请找到编辑的问题。 – 2014-09-10 10:04:20