Awk jq仅替换json文件中某些行的一部分中出现的多个字符

Awk jq仅替换json文件中某些行的一部分中出现的多个字符,awk,sed,jq,Awk,Sed,Jq,我有一组包含如下部分的文件: "billing_date": { "type": "date", "meta": { "display": "Billing Date", "format": ":%x" } }, "billing_accounting_date": { "type": "date", "meta": {

我有一组包含如下部分的文件:

    "billing_date": {
        "type": "date",
        "meta": {
            "display": "Billing Date",
            "format": ":%x"
        }
    },
    "billing_accounting_date": {
        "type": "date",
        "meta": {
            "display": "Billing Accounting Date",
            "format": ":%x"
        }
    }
我需要将“display”字段的内容更改为使用下划线而不是空格,因此结果如下所示(请注意,Billing_Date和Billing_Accounting_Date中的下划线):

皮埃尔·弗朗索瓦善意地建议使用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”中的
spine
实用程序

使用
walk

您可能还希望考虑使用<代码> Wave,例如沿着:

walk(if type == "object" and has("display") then .display |= gsub(" "; "_") else . end)

您最好使用
jq
作为修改JSON文件的工具。感谢Pierre François的建议!我会试试jq。。
walk(if type == "object" and has("display") then .display |= gsub(" "; "_") else . end)