【问题标题】:Compare two files and make union比较两个文件并合并
【发布时间】:2013-09-11 21:51:31
【问题描述】:

我测试了下面的一行来比较 2 个文件中的第一列并进行联合。然而,file2 中第一列相同的不同值被消除了。下面我附上了示例文件、获得的结果和期望的结果。请你帮帮我。

awk -F, 'BEGIN{OFS=","}FNR==NR{a[$1]=$1","$2;next}($1 in a && $2=$2","a[$1])' file2.csv file1.csv >testout.txt

file1
John,red
John,blue
Mike,red
Mike,blue
Carl,red
Carl,blue

file2
John,V1
John,V2
Kent,V1
Kent,V2
Mike,V1
Mike,V2

obtained result
John,red,John,V2
John,blue,John,V2
Mike,red,Mike,V2
Mike,blue,Mike,V2

desired result
John,red,John,V1
John,red,John,V2
John,blue,John,V1
John,blue,John,V2
Mike,red,Kent,V1
Mike,red,Kent,V2
Mike,blue,Kent,V1
Mike,blue,Kent,V2

【问题讨论】:

  • Mike,red,Kent,V1 Mike,red,Kent,V2 etc. 是错字吗?

标签: join awk compare union two-columns


【解决方案1】:

试试这个单线:

 awk -F, -v OFS="," 'NR==FNR{a[$0];next}{for(x in a)if(x~"^"$1FS)print $0,x}' file2 file1

测试:

kent$  awk -F, -v OFS="," 'NR==FNR{a[$0];next}{for(x in a)if(x~"^"$1FS)print $0,x}' f2 f1
John,red,John,V1
John,red,John,V2
John,blue,John,V1
John,blue,John,V2
Mike,red,Mike,V1
Mike,red,Mike,V2
Mike,blue,Mike,V1
Mike,blue,Mike,V2

【讨论】:

  • 您能解释一下您在if(x~"^"$1FS) 中究竟做了什么吗? @肯特
  • @user2770199 "^"$1FS 构建一个正则表达式,例如^John, 我们检查 John,red 是否与正则表达式匹配。
【解决方案2】:

使用join 可以做到这一点:

join -t, -1 1 -2 1 --nocheck-order -o 1.1 1.2 2.1 2.2 file1 file2

输出:

John,red,John,V1
John,red,John,V2
John,blue,John,V1
John,blue,John,V2
Mike,red,Mike,V1
Mike,red,Mike,V2
Mike,blue,Mike,V1
Mike,blue,Mike,V2

【讨论】:

    猜你喜欢
    • 2017-10-25
    • 1970-01-01
    • 1970-01-01
    • 2017-11-22
    • 1970-01-01
    • 2019-11-15
    • 2015-12-05
    • 1970-01-01
    • 2011-12-15
    相关资源
    最近更新 更多