我有一组包含如下部分的文件:
"billing_date": {
"type": "date",
"meta": {
"display": "Billing Date",
"format": ":%x"
}
},
"billing_accounting_date": {
"type": "date",
"meta": {
"display": "Billing Accounting Date",
"format": ":%x"
}
}
我需要更改“显示”字段的内容以使用下划线而不是空格,因此结果如下(注意 Billing_Date 和 Billing_Accounting_Date 中的下划线):
"billing_date": {
"type": "date",
"meta": {
"display": "Billing_Date",
"format": ":%x"
}
},
"billing_accounting_date": {
"type": "date",
"meta": {
"display": "Billing_Accounting_Date",
"format": ":%x"
}
}
Pierre Francois 好心建议使用 jq;我一直在尝试,但仍然无法将它们组合在一起。
每个文件都有几十个不同的字段;我已经能够提取所需的替换内容,但不知道如何将它们放回到文件中。
% jq '.mappings.properties[].meta.display' input.txt
"Key"
"Action"
"Transaction Import Time"
"Hash"
"Data Exchange 1.0 Warnings"
"Data Exchange 1.0 Errors"
"Effective Time"
"Import ID"
"Import S3 Key"
"Importing User Name"
"Utility UUID"
"Utility Name"
"Import File Row"
"Account ID"
"Location ID"
"Service Point ID"
"Meter ID"
"Bill ID"
"Register Number"
"Billing Unit Of Measure"
"Billing Cycle Start Date"
"Billing Cycle End Date"
"Billing Cycle Start Read"
"Billing Cycle End Read"
"Billing Cycle Consumption"
"Billing Date"
"Billing Accounting Date"
% jq '.mappings.properties[].meta.display | sub(" "; "_") | sub(" "; "_") | sub(" "; "_") | sub(" "; "_")' input.txt
"Key"
"Action"
"Transaction_Import_Time"
"Hash"
"Data_Exchange_1.0_Warnings"
"Data_Exchange_1.0_Errors"
"Effective_Time"
etc...
最佳答案
以下 jq 过滤器可用于在一次 jq 调用中实现所需的结果:
.billing_date.meta.display |= gsub(" "; "_")
| .billing_accounting_date.meta.display |= gsub(" "; "_")
或者也许这就是您想要的:
.mappings.properties[].meta.display |= gsub(" "; "_")
如果您愿意冒险覆盖输入文件,您可能会喜欢使用“coreutils”中的sponge
实用程序。
使用步行
您可能还希望考虑使用walk
,例如大致如下:
walk(if type == "object" and has("display") then .display |= gsub(" "; "_") else . end)
关于awk - jq 仅替换 json 文件的某些行的一部分中多次出现的字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61526906/