0

I have something like this in file and I want to change few values

My file data

variable "my_vnets" {
  default = {
    transit_vnet = {
      name       = "dummy"
      cidr       = "11.1.1.1.1."
      is_transit = false
    }
    spoke1_vnet = {
      name       = "dummy2"
      cidr       = "1.1.1.1.1"
      is_transit = false
    }
  }
}

expected output

variable "my_vnets" {
  default = {
    transit_vnet = {
      name       = "NewName"
      cidr       = "11.1.1.1.1."
      is_transit = true
    }
    spoke1_vnet = {
      name       = "NewName2"
      cidr       = "2.2.2.2"
      is_transit = false
    }
  }
}

I am trying something like this but no luck

sed -i "s/\"my_vnets\" { default = \"""\" }/\"my_vnets\" { default = \""NewName"\" }/g"
2
  • Does this answer your question? change json file by bash script Commented Nov 30, 2020 at 19:35
  • @Lenna, that's not JSON though. Commented Nov 30, 2020 at 19:58

1 Answer 1

1

In general, usage of structure-unaware tools to edit structured files should be avoided. However, if there aren't any structured tools for parsing and generating this format, consider something like:

sed -r -e '/^[[:space:]]+name[[:space:]]+=/ { s/dummy/NewName/; }' \
       -e '/transit_vnet = [{]/,/[}]/       { s/is_transit = false/is_transit = true/; }'

...replacing dummy with NewName only on lines that start with name = ; and is_transit = false with is_transit = true only after a match for transit_vnet = { and before a match for }.

Sign up to request clarification or add additional context in comments.

12 Comments

thanks for reply sir , there is one constraint . for example I want to change is_transit value then whole file consisting of 'is_transit' variable will be changed. thats why I need to be specific to a variable .
I don't think your question currently specifies that constraint -- your sample data edits both names.
...that said, does applying that edit between the line transit_vnet { and the next-following line with only a } work?
I have ` default = { transit_vnet = { name = "NewName" cidr = "11.1.1.1.1." is_transit = true } spoke1_vnet = { name = "NewName2" cidr = "2.2.2.2" is_transit = false }` 2 is_transit variables . So I just want to change one of them
See the edit, changing is_transit only inside the transit_vnet block.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.