Shahroz Pervaz
Shahroz Pervaz

Reputation: 73

change variable values using sed command

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"

Upvotes: 0

Views: 361

Answers (1)

Charles Duffy
Charles Duffy

Reputation: 295795

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 }.

Upvotes: 1

Related Questions