Join 比较两个文件并建立联合
我测试了下面的一行,比较了两个文件中的第一列,并建立了一个联合。但是,文件2中第1列相同的不同值被删除。下面我附上了样本文件、获得的结果和期望的结果。你能帮助我吗Join 比较两个文件并建立联合,join,awk,compare,union,two-columns,Join,Awk,Compare,Union,Two Columns,我测试了下面的一行,比较了两个文件中的第一列,并建立了一个联合。但是,文件2中第1列相同的不同值被删除。下面我附上了样本文件、获得的结果和期望的结果。你能帮助我吗 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 C
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
试试这一行:
awk -F, -v OFS="," 'NR==FNR{a[$0];next}{for(x in a)if(x~"^"$1FS)print $0,x}' file2 file1
测试:
使用
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
Mike,red,Kent,V1
Mike,red,Kent,V2
等。这是打字错误吗?如果(x~“^”$1FS),你能解释一下你在中到底做了什么吗@Kent@user2770199“^”$1FS
构建正则表达式,例如^John,
我们检查John,red
是否与正则表达式匹配。
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