用于在文件中添加数据的 shell 脚本 [重复]
Posted
技术标签:
【中文标题】用于在文件中添加数据的 shell 脚本 [重复]【英文标题】:shell script for adding data in file [duplicate] 【发布时间】:2022-01-07 11:03:39 【问题描述】:我在 linux env 中有文件说 sample1.txt 用逗号分隔值:下面
"zc52","FS_SE",20-JUN-19,"P1C217.DB.ATC.COM - 636",""
"p214","FS_MG",16-OCT-20,"",""
"x901","FS_TC",01-APR-21,"",""
"r750","FS_SP",06-JUL-21,"",
我需要具有 100 万条记录的以下格式的输出,我该怎么做。
"id":"zc52","role":"FS_SE","created_time_stamp":"20-JUN-19, q_id":"P1C217.DB.ATC.COM - 636"
"id":"p214","role":"FS_MG","created_time_stamp":"16-OCT-20"
"id":"x901","role":"FS_TC","created_time_stamp":"01-APR-21"
"id":"r750","role":"FS_SP","created_time_stamp":"06-JUL-21"
【问题讨论】:
这能回答你的问题吗? Converting CSV to JSON in bash 谢谢,你能提供我如何将这些添加到我的脚本中以获取上述数据。 你被困在哪里了? SO 在这里帮助现有的代码尝试。请edit你的问题。谢谢。 【参考方案1】:我会为此任务选择其他语言,因为使用 bash 准确解析引用的 CSV 有点困难。
使用 Ruby 真的很简单:
echo 'id,role,created_time_stamp,q_id' |
ruby -rcsv -rjson -e 'CSV.new(ARGF, headers: true).each|r| puts r.to_hash.reject|_,v| v.empty?.to_json' - file.csv
file.csv
:
"zc52","FS_SE",20-JUN-19,"P1C217.DB.ATC.COM - 636",""
"p214","FS_MG",16-OCT-20,"",""
"x901","FS_TC",01-APR-21,"",""
"r750","FS_SP",06-JUL-21,"",""
输出:
"id":"zc52","role":"FS_SE","created_time_stamp":"20-JUN-19","q_id":"P1C217.DB.ATC.COM - 636"
"id":"p214","role":"FS_MG","created_time_stamp":"16-OCT-20"
"id":"x901","role":"FS_TC","created_time_stamp":"01-APR-21"
"id":"r750","role":"FS_SP","created_time_stamp":"06-JUL-21"
备注:您要生成的不是有效的 JSON,而是一堆 JSON 对象。
【讨论】:
以上是关于用于在文件中添加数据的 shell 脚本 [重复]的主要内容,如果未能解决你的问题,请参考以下文章