3

我想使用 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

4

1 回答 1

3

您能否尝试在 GNU 中使用显示的示例进行跟踪、编写和测试awk

awk -F'[[:space:]]*,[[:space:]]*' -v s1="\"" '
FNR==1{
  for(i=2;i<=NF;i++){
    gsub(/^ +| +$/,"",$i)
    arr[i]=$i
  }
  next
}
{
  print "["$1"]"
  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 "["$1"]"                                  ##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 的第一行的最后没有找到空格,则将其删除。

于 2020-10-06T11:23:30.267 回答