1

I would like to udpate a file config.yaml file by inserting some configuration parameters via bash.

The file to be updated looks like:

{
  "log": [
    {
      "format": "plain",
      "level": "info",
      "output": "stderr"
    }
  ],
  "p2p": {
    "topics_of_interest": {
      "blocks": "normal",
      "messages": "low"
    },
    "trusted_peers": [
      {
        "address": "/ip4/13.230.137.72/tcp/3000",
        "id": "fe3332044877b2034c8632a08f08ee47f3fbea6c64165b3b"
      }
    ]
  },
  "rest": {
    "listen": "127.0.0.1:3100"
  }
}

And it needs to look like:

{
  "log": [
    {
      "format": "plain",
      "level": "info",
      "output": "stderr"
    }
  ],
  "storage": "./storage",
  "p2p": {
    "listen_address":"/ip4/0.0.0.0/tcp/3000",
    "public_address":"/ip4/0.0.0.0/tcp/3000",
    "topics_of_interest": {
      "blocks": "normal",
      "messages": "low"
    },
    "trusted_peers": [
      {
        "address": "/ip4/13.230.137.72/tcp/3000",
        "id": "fe3332044877b2034c8632a08f08ee47f3fbea6c64165b3b"
      }
    ]
  },
  "rest": {
    "listen": "127.0.0.1:3100"
  }
}

so adding

  • on the first level "storage": "./storage",
  • and on the second level in the p2p section "listen_address":"/ip4/0.0.0.0/tcp/3000", and "public_address":"/ip4/0.0.0.0/tcp/3000",

How do I do this with sed?

For YAML to JSON editor checkout---YAML to JSON editor

krutik k
  • 5
  • 2
Tino
  • 3,340
  • 5
  • 44
  • 74
  • 1
    may I interest you in this link: [RegEx match XHTML](https://stackoverflow.com/a/1732454/2805305) Although yaml might not be as complicated as html, the principle I think applies. Pick a tool fit for the job. Bash to edit yaml and json files is a bad idea imho. Is python an option? – bolov Dec 15 '19 at 15:41
  • It would be nice if only done via bash, but if not possible then python can be an option. – Tino Dec 15 '19 at 15:59
  • `on the second level in the p2p section` - this is (almost) impossible in `sed`, and even it is possible, it is very, very hard to do. Are you *sure* this is a yaml file? Because [this validator available online](https://codebeautify.org/yaml-validator) can't parse it and it looks like a json file. To parse json use `jq` utility. – KamilCuk Dec 15 '19 at 16:30
  • YAML is a superset of JSON, so if it's valid JSON, it's valid YAML as well. I don't know what issue that validator has with it, but the snippet shown is valid. – chepner Dec 15 '19 at 17:13

1 Answers1

0

If you are certain that your YAML file is written in the JSON subset of YAML, you can use jq:

jq --arg a "/ip4/0.0.0.0/tcp/3000" \
  '.storage = "./storage" |
   .php += {listen_address: $a, public_address: $a}' config.yaml > tmp &&
mv tmp config.yaml
chepner
  • 497,756
  • 71
  • 530
  • 681