Dave
Dave

Reputation: 19150

In bash, how can I search and replace over multiple lines in a yaml file?

I’m using bash shell. I have a series of YAML files formatted like so

qa:
  property1: abcdef
  property2: xyzhijkl
  …

production:

I would like to write a script to copy everything between the “qa” and “production” blocks to put the properties under "qa" into an additional "qa2" block. The above would be converted to

qa:
  property1: abcdef
  property2: xyzhijkl
  …

qa2:
  property1: abcdef
  property2: xyzhijkl
  …

production:

Is there a way I could write a bash script to do the search and replacement?

Upvotes: 0

Views: 733

Answers (2)

sseLtaH
sseLtaH

Reputation: 11227

If sed is an option

$ sed -n '/^qa/,/^$/{P;s/^qa/qa2/;H;d};x;p;' input_file
qa:
  property1: abcdef
  property2: xyzhijkl
  …


qa2:
  property1: abcdef
  property2: xyzhijkl
  …

production:

Upvotes: 0

flyx
flyx

Reputation: 39688

Trivial solution using yq:

yq e '.qa2 = .qa' test.yaml

This will put qa2 after production, which shouldn't matter because that has the exact same semantics according to the YAML spec. If you still dislike it, put it before production by removing that and adding it back later:

yq e '.production as $p | del(.production) | .qa2 = .qa | .production = $p' test.yaml

Upvotes: 1

Related Questions