小编al7*_*l76的帖子

使用 sub() 函数有条件地更改 jq 中的 JSON 值

我需要更改 JSON 数据中的一些值,并希望将其包含在现有的 shell 脚本中。我正在尝试使用 jq 来执行此操作,并且需要“sub()”函数来截断字符串值的一部分。

使用此命令行:

jq '._meta[][].ansible_ssh_pass | sub(" .*" ; "")'
Run Code Online (Sandbox Code Playgroud)

使用下面的数据将正确替换该值(切断任何内容,包括数据中的第一个空格),但仅打印出该值,而不是完整的 JSON 结构。

以下是 JSON 数据示例:

{_meta": {
    "hostvars": {
      "10.1.1.3": {
        "hostname": "core-gw1",
        "ansible_user": "",
        "ansible_ssh_pass": "test123 / ena: test2",
        "configsicherung": "true",
        "os": "ios",
        "managementpaket": ""
      }
    }
}}
Run Code Online (Sandbox Code Playgroud)

输出应该是这样的:

{"_meta": {
    "hostvars": {
      "10.1.1.3": {
        "hostname": "core-gw1",
        "ansible_user": "",
        "ansible_ssh_pass": "test123",
        "configsicherung": "true",
        "os": "ios",
        "managementpaket": ""
      }
    }
}}
Run Code Online (Sandbox Code Playgroud)

我认为我必须添加某种基于“如果...那么”的参数,但无法让 jq 理解我;)手册有点粗略,我找不到任何示例可以与我需要做的事情相匹配......

shell json jq

4
推荐指数
1
解决办法
3622
查看次数

标签 统计

jq ×1

json ×1

shell ×1