微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决如何使用AWK将CSV文件转换为TOML哈希表

我想使用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 "["$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)正在使用,如果在第一行的末尾没有找到空格,请删除此行输入文件的行。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。