Home > Enterprise >  Replace yaml config with sed
Replace yaml config with sed

Time:09-23

I have the following yaml file called file.yaml

# This is a file store

  - file-store:
      version: 2
      enabled: no

  - file-store2:
      version: 4
      enabled: yes

Is there a way to enable the file-store option for the first group?. I tried to use this one but it doesn't work:

sed -i '/^ *file-store:/,/^ *[^:]*:/s/enabled: no/enabled: yes/' file.yaml

  

Expected output:

  # This is a file store

  - file-store:
      version: 2
      enabled: yes

  - file-store2:
      version: 4
      enabled: yes

CodePudding user response:

You can use yq

$ cat file
  file1:
      version: 2
      enabled: no

   file2:
      version: 4
      enabled: yes

To change the value of enabled, use:

$ yq -e '.file1.enabled = "yes"' file
{
  "file1": {
    "version": 2,
    "enabled": "yes"
  },
  "file2": {
    "version": 4,
    "enabled": true
  }
}

To save in place, add -yi flag

As your question includes sed, here is a fragile solution

$ sed '/file1/ {n;N;s/no/yes/}' file
   file1:
      version: 2
      enabled: yes

   file2:
      version: 4
      enabled: yes

CodePudding user response:

In addition to the recommendations given by @HatLess you can try to use this pure sed solution. I know, it's too wordy but it's more reliable even though not 100%.

# Capture the block between "- file-store:" and "- file store.*:"
/^[ ]*- file-store:/,/^[ ]*- file-store[^:]*:/ {
    # Look for te string having "enabled:"
    # and replace the last non-whitespace sequence with "yes"
    /enabled:/ s/[^ ][^ ]*$/yes/
}

and the short inline version of the script:

sed '/^[ ]*- file-store:/,/^[ ]*- file-store[^:]*:/ { /enabled:/ s/[^ ][^ ]*$/yes/ }'
  • Related