You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

请求修复AWK脚本以实现指定CSV数据转换需求

AWK脚本修复:处理CSV数据并按规则转换输出

需求说明

需修复现有AWK脚本,实现以下规则并修正输出格式:

  • 将prob_id字段的1-5依次重命名为3_a至3_e
  • 分数转换规则:输入score为1时输出0;输入score为0时,对应prob_id1输出10,prob_id2-5输出5
  • 输出需严格匹配指定的CSV列结构:Identifier,prob_id,score,comments

原始脚本

#!/usr/bin/awk -f

BEGIN {
  print "Identifier,prob_id,score,comments"
  FS = "," 
}
{
  if (NR>1)
    print "Participant",$1,$4
}

原始CSV数据

Identifier,prob_id,score,prob_desc
748737,1,0,code compiles
748737,2,0,input 101
748737,3,0,input 10011
748737,4,0,empty input
748737,5,0,bad input
748708,1,0,code compiles
748708,2,0,input 101
748708,3,1,input 10011
748708,4,0,empty input
748708,5,1,bad input
748701,1,0,code compiles
748701,2,0,input 101
748701,3,0,input 10011
748701,4,0,empty input
748701,5,1,bad input

当前错误输出

Identifier,prob_id,score,comments
Participant 748737 code compiles
Participant 748737 input 101
Participant 748737 input 10011
Participant 748737 empty input
Participant 748737 bad input
Participant 748708 code compiles
Participant 748708 input 101
Participant 748708 input 10011
Participant 748708 empty input
Participant 748708 bad input
Participant 748701 code compiles
Participant 748701 input 101
Participant 748701 input 10011
Participant 748701 empty input
Participant 748701 bad input

预期输出

Identifier,prob_id,score,comments
Participant 748737,3_a,10,code compiles
Participant 748737,3_b,5,input 101
Participant 748737,3_c,5,input 10011
Participant 748737,3_d,5,empty input
Participant 748737,3_e,5,bad input
Participant 748708,3_a,10,code compiles
Participant 748708,3_b,5,input 101
Participant 748708,3_c,0,input 10011
Participant 748708,3_d,5,empty input
Participant 748708,3_e,0,bad input
Participant 748701,3_a,10,code compiles
Participant 748701,3_b,5,input 101
Participant 748701,3_c,5,input 10011
Participant 748701,3_d,5,empty input
Participant 748701,3_e,0,bad input

修复后的脚本

#!/usr/bin/awk -f

BEGIN {
  print "Identifier,prob_id,score,comments"
  FS = ","
  # 定义prob_id映射关系
  prob_map[1] = "3_a"
  prob_map[2] = "3_b"
  prob_map[3] = "3_c"
  prob_map[4] = "3_d"
  prob_map[5] = "3_e"
  # 定义score为0时的对应输出分数
  score_map[1] = 10
  score_map[2] = 5
  score_map[3] = 5
  score_map[4] = 5
  score_map[5] = 5
}

NR > 1 {
  # 处理prob_id转换
  new_prob_id = prob_map[$2]
  # 处理score转换
  if ($3 == 1) {
    new_score = 0
  } else {
    new_score = score_map[$2]
  }
  # 按CSV格式输出,注意字段分隔符为逗号
  printf "Participant %s,%s,%d,%s\n", $1, new_prob_id, new_score, $4
}

关键修改说明

  1. 添加映射数组:在BEGIN块中定义prob_map和score_map,分别存储prob_id的重命名规则和score为0时的对应输出值,逻辑清晰易维护。
  2. 分数转换逻辑:根据输入的score值($3)判断,若为1则输出0,否则从score_map中获取对应prob_id的分数。
  3. 输出格式修正:使用printf严格控制CSV格式,确保字段用逗号分隔,完全匹配预期输出结构。

内容的提问来源于stack exchange,提问作者Hammad Shabir

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 00:40:27