【问题标题】:How can I transform a CSV file to a TOML hash table using AWK如何使用 AWK 将 CSV 文件转换为 TOML 哈希表
【发布时间】:2020-10-06 19:31:01
【问题描述】:

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

【问题讨论】:

    标签: awk toml


    【解决方案1】:

    您能否尝试在 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 在第一行有空格以将其删除输入文件。

    【讨论】:

      猜你喜欢
      • 2011-05-30
      • 2012-12-21
      • 1970-01-01
      • 2019-08-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-10
      • 1970-01-01
      相关资源
      最近更新 更多