'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?



Solution 1:[1]

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

Solution 2:[2]

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:

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 flyx
Solution 2 HatLess