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

标签 awk sed jq

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

    "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/

相关文章:

linux - 按列将大型 CSV 拆分为多个文件

linux - 使用 awk 生成报告

bash - 我可以将文件用作 awk 的模式以从其他文件列表中删除吗?

regex - 非贪婪模式表达式

json - 按子元素查找元素并替换为子元素的值

arrays - 使用 jq 向现有 JSON 数组添加新元素

linux - Bash:循环从 CSV 中一次读取 N 行

bash - 在 shell 脚本中提取引号中的单词

python - 如何从嵌套的 csv 文件中删除子列?

git - 如何对多个文件并行运行递归查找和替换操作?