如何使用 AWK 将 CSV 文件转换为 TOML 哈希 table

How can I transform a CSV file to a TOML hash table using AWK

我想使用 AWK 将 CSV 文件转换为 TOML。我的输入如下所示:

id , name , lifetime   
adam , Adam , 1550-1602
eve , Eve , 1542-1619

我正在努力做到这一点

[adam]
  name = "Adam"
  lifetime = "1550-1602"
[eve]
  name = "Eve"
  lifetime = "1542-1619"

我制作了以下 AWK 小脚本,但不太成功:

BEGIN {
  FS=","
  }
NR == 1 {
  nc = NF
  for (c = 1; c <= NF; c++) {
    h[c] = $c
    }
  }
NR > 1 {
  for(c = 1; c <= nc; c++) {
    printf h[c] "= " $c "\n"
    }
    print ""
   }
END {    
  }

目前的结果是这样

id = adam
 name =  Adam 
 lifetime=  1550-1602

id = eve 
 name =  Eve 
 lifetime=  1542-1619

郑重声明,我的 AWK 版本是 GNU Awk 4.1.4

您能否尝试在 GNU awk.

中使用显示的示例进行跟踪、编写和测试
awk -F'[[:space:]]*,[[:space:]]*' -v s1="\"" '
FNR==1{
  for(i=2;i<=NF;i++){
    gsub(/^ +| +$/,"",$i)
    arr[i]=$i
  }
  next
}
{
  print "[""]"
  for(i=2;i<=NF;i++){
    print "  "arr[i]" = "s1 $i s1
  }
}' Input_file

说明:为上述解决方案添加详细说明。

awk -F'[[:space:]]*,[[:space:]]*' -v s1="\"" '    ##Starting awk program from here, setting field separator as space comma space and creating variable s1 which has " in it.
FNR==1{                                           ##Checking condition if this is first line then do following.
  for(i=2;i<=NF;i++){                             ##Run a for loop from 2nd field to last field in current line.
    gsub(/^ +| +$/,"",$i)                         ##Globally substituting spaces from starting or ending to NULL in current field.
    arr[i]=$i                                     ##Creating arr with index of i and value of $i here.
  }
  next                                            ##next will skip all further statements from here.
}
{
  print "[""]"                                  ##Printing [ first field ] here.
  for(i=2;i<=NF;i++){                             ##Running loop from 2 to till last field of line here.
    print "  "arr[i]" = "s1 $i s1                 ##Printing arr value with index i and s1 current field s1 here.
  }
}' Input_file                                     ##Mentioning Input_file name here.

注意: OP 的示例 Input_file 在第一行有空格以删除它们 gsub(/^ +| +$/,"",$i) 正在如果在 Input_file.

的第一行最后没有找到空格,则使用删除它