awk根据键值匹配并合并两个文件

时间:2013-10-25 07:14:02

标签: bash join sed awk

我有两个文件$3,$4 = $3,$2

文件1:

1211,A2,ittp,1,IPSG,a2,PA,3000,3000  
1311,A4,iztv,1,IPSG,a4,PA,240,250  
1411,B4,iztq,0,IPSG,b4,PA,230,250  

file2的:

TP,0,nttp,0.865556,0.866667  
TP,1,ittp,50.7956,50.65  
TP,1,iztv,5.42444,13.8467  
TP,0,iztq,645.194,490.609  

我想合并这些文件并打印一个新文件,如file1 $3,$4 = file2 $3,$2然后打印合并文件,如

TP,1211,A2,ittp,1,IPSG,a2,PA,3000,3000,0.865556,0.866667  
TP,1311,A4,iztv,1,IPSG,a4,PA,240,250,50.7956,50.65  
TP,1411,B4,iztq,0,IPSG,b4,PA,230,250,5.42444,13.8467     

这些文件都是CSV文件。

我尝试使用awk,但我没有得到所需的输出。它只打印file1。

$ awk -F, 'NR==FNR{a[$3,$4]=$3$2;next}{print $1, $2, $3, $4, $5, $6, $7, $8, $9, $10 a[$1] }' OFS=, 1.csv 2.csv  

3 个答案:

答案 0 :(得分:1)

awk -F, 'BEGIN {OFS=",";}
         NR == FNR {a[$3,$4] = $0;}
         NR != FNR && a[$3,$2] {print $1, a[$3,$2], $4, $5;}' 1.csv 2.csv

答案 1 :(得分:0)

awk的一种方式:

awk 'NR==FNR{a[$4,$3]=$0;next}($2,$3) in a{print $1,a[$2,$3],$4,$5}' FS=, OFS=, f1 f2
TP,1211,A2,ittp,1,IPSG,a2,PA,3000,3000,50.7956,50.65
TP,1311,A4,iztv,1,IPSG,a4,PA,240,250,5.42444,13.8467
TP,1411,B4,iztq,0,IPSG,b4,PA,230,250,645.194,490.609

答案 2 :(得分:0)

使用加入 如果i1和i2是输入文件

cat i1.txt | awk -F',' '{print $3 "-" $4 "," $1 "," $2 "," $5 "," $6 "," $7 "," $8 "," $9}' | sort > s1.txt
cat i2.txt | awk -F',' '{print $3 "-" $2 "," $1 "," $4 "," $5 }' | sort > s2.txt
join -t',' s1.txt s2.txt | tr '-' ',' > t12.txt
cat t12.txt | awk -F ',' '{print $10 "," $3 "," $4 "," $1 "," $2 "," $5 "," $6 "," $7 "," $8 "," $9 "," $11 "," $12 }'