Saturday, May 18, 2024
0
rated 0 times [  0] [ 0]  / answers: 1 / hits: 478  / 1 Year ago, sun, march 5, 2023, 8:18:35

I have a file with data like the following. xyz can be anything, so I want to replace it.


variable "azure_spoke_gateways" {
default = {
spoke1 = {
name = "xyz"
size = "max"
vpc = "azure_spoke1_vnet"
},
}
}

variable "google_spoke_gateways" {
default = {
spoke1 = {
name = "xyz"
size = "max"
vpc = "azure_spoke1_vnet"
},
}
}

I just want to replace value of variable azure_spoke_gateways's name. The desired output is:


  variable "azure_spoke_gateways" {
default = {
spoke1 = {
name = "MYSTRING"
size = "max"
vpc = "azure_spoke1_vnet"
},
}
}

More From » command-line

 Answers
3

Usually, you can parse line by line on simpler formats, as long as you keep track of the subsection.


awk '  
match($0,/variable "([^"]+)" {/,m) {
v = m[1]
}
$1 ~ /name/{
if(v == "azure_spoke_gateways") {
gsub(/"[^"]+"$/, ""MYSTRING"", $0)
}
} 1' data

You could also make it as a script file.


#!/usr/bin/awk -f

match($0,/variable "([^"]+)" {/,m) {
v = m[1]
}
v == "google_spoke_gateways" {
if($1 == "name"){
gsub(/"[^"]+"$/, ""MYSTRING"", $0)
}
if($1 == "size") {
gsub(/"[^"]+"$/, ""min"", $0)
}
if($1 == "vpc") {
gsub(/"[^"]+"$/, ""google_spoke1_vnet"", $0)
}
} 1

And you run the script like this.


awk -f script.awk < data

[#2248] Monday, March 6, 2023, 1 Year  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
ainubt

Total Points: 496
Total Questions: 98
Total Answers: 126

Location: Sao Tome and Principe
Member since Wed, Dec 21, 2022
1 Year ago
;