如何使用 awk 比较和替换特定位置的值

如何使用 awk 比较和替换特定位置的值

我想比较csv具有一个公共列的两个文件,然后在特定位置将第一个文件中的数据替换为第二个文件中的数据。

文件1.csv:

"id","name","marks","subject","result"
"1","a","","art",""
"4","c","","math",""
"3","b","","history",""
"5","d","","comerce",""

文件2.csv:

"id","marks","result"
"4","40","pass"
"3","30","fail"
"1","20","fail"
"6","10",""
"5","10",""

输出应该是:

"id","name","marks","subject","result"
"1","a","20","art","fail"
"4","c","40","math","pass"
"3","b","30","history","fail"
"5","d","10","comerce",""

我正在使用awk如下语句,但是它最终合并了值,而不是在特定位置添加:

awk 'NR==FNR{a[$1]=$2; b[$1]=$3; next}  {print $0, a[$2], b[$2] } file1.csv file2.csv 

答案1

awk '
  BEGIN{OFS=FS=","} 
  NR==FNR {
    marks[$1]=$2; status[$1]=$3; next
  } 
  $1 in marks {$3 = marks[$1]} 
  $1 in status {$5 = status[$1]}
  1' file2.csv file1.csv
"id","name","marks","subject","result"
"1","a","20","art","fail"
"4","c","40","math","pass"
"3","b","30","history","fail"
"5","d","10","comerce",""

相关内容