Reputation: 5092
A example of env.yaml file is shown below
package:
name: "xyz"
version: "2.3.1"
build:
noarch: python
requirements:
build:
- python
how to add a build/number:123
to the yaml file with correct indentation as follows?
package:
name: "xyz"
version: "2.3.1"
build:
noarch: python
number: 123
requirements:
build:
- python
The tricky thing is, there is a build key under requirement section, and I don't want any number added under that
Upvotes: 0
Views: 1315
Reputation: 58488
This might work for you (GNU sed):
sed -E '/^\s+\S/h;/^build:/{:a;n;/^$/!ba;x;s/\S.*/number: 123/p;x}' file
Make a copy of any indented line and then append the copy (replacing its content by the desired result) at the end of the build:
stanza.
N.B. This is based on the data provided, the programmer can be more specific and choose an indented line like name:
in the package:
stanza if s/he prefers.
Upvotes: 0
Reputation: 204258
sed is the best tool for doing simple s/old/new/ on individual strings, that is all. For anything more than that you should use awk (assuming you don't have access to a tool that understands whatever language your input file is written in, if applicable)
$ cat tst.awk
/^build:/ { f=1 }
!NF { prt(); f=0 }
{ print; prev=$0 }
END { prt() }
function prt() {
if (f) {
sub(/[^[:space:]].*/,"",prev)
print prev "number: 123"
}
}
$ awk -f tst.awk file
package:
name: "xyz"
version: "2.3.1"
build:
noarch: python
number: 123
requirements:
build:
- python
Upvotes: 2
Reputation: 476
If sed is to be used, and assuming the line sequence is fixed and that both the file content order is fixed and the values to insert:
sed -ri 's/^(\s+)noarch: python/&\n\1job: 123/' env.yaml
Upvotes: 1