mardi 21 septembre 2021

Need help on bask awk to update Yaml file by finding the pattern in the file

CONTEXT: I am very new to UNIX scripting and bash.

I have a .bash script that takes a .yaml and an array of VMs passed as arguments.

(e.g.)

myscript.sh my.yaml neo1 neo2 neo3 alice1 alice2 alice3

How to find the monitor_vm key pattern and file the last lime of the that monitor section and add at the last lines of that section?

Have got one sample function which identifies some pattern to give line number of that inserting line ....but it requires some changes. Please advise example

getline() {
  awk '
    BEGIN { monitor_vms="'${}'"; ln=1; fnd=0; }
      (fnd==1 && $0 ~ /^  [a-z]/) { exit }
      ($0~/^monitor_vms:/) { fnd = 1 }
      ($0 ~ /./ && $0 !~ /^#/) { ln = NR }
    END { print ln }' ${1}
}


for name in $VM_LIST; do
  line=`getline my.yaml monitor_vms`
  sed -i -e ${line}"a\- name: \"${vmname}\"\n my.yaml
done

The file my.yaml looks like the following:

----
- someotherkey: hello
  value: some_value
- someotherkey1: hello1
  value1: some_value1
- monitor_vms:
  - name:  sujana
    cnt: 5
  - name: vijaya
    cnt: 5
- static_configs:
  - location:
    datacenter: 

I would expect to produce the required my.yaml, after update:

---
- someotherkey: hello
  value: some_value
- someotherkey1: hello1
  value1: some_value1
- monitor_vms:
  - name:  sujana
    cnt: 5
  - name: vijaya
    cnt: 5
  - name: neo1
  - name: neo2
  - name: neo3
  - name: alice1
  - name: alice2
  - name: alice3
- static_configs:
  - location:
    datacenter: 

Aucun commentaire:

Enregistrer un commentaire