Home > Enterprise >  Controlled Iteration through bash array using nested for loop
Controlled Iteration through bash array using nested for loop

Time:04-20

common.yml file

tomcat9_version:               "9.0.64-154"
openjdk11_version:                "11.54.24-95"
newrelic_infra_agent_version:  "0.1.22-42"

vars.yml

Tomcat:
  packages:
    OpenJDK11:
      - 11.52.24
    Tomcat9:
      - 9.0.50
   newrelic_infra:
      - 0.1.21

Capture values of tomcat9_version, openjdk11_version, newrelic_infra_agent_version from common.yml and replace OpenJDK11, Tomcat9, newrelic_infra values in vars.yml

What i wrote

#!/bin/bash
declare -a arr=("openjdk11_version" "tomcat9_version" "newrelic_infra_agent_version")
declare -a brr=("OpenJDK11:" "Tomcat9:" "newrelic_infra:")
for i in "${arr[@]}"
do
   value=$(grep "$i" common.yaml  | awk '{print $NF}')
   echo "$value"
    for i in "${brr[@]}"
    do
      pakru=$(awk -v var=$i '$1 == "-"{ if (key == var) print $NF;next } {key=$1}' vars.yaml)
      echo "$pakru"
      sed -i "s/$pakru/$value/g" "vars.yaml"
      break
   done
done

The output i got

"11.54.24-95"
11.52.24
9.0.50
0.1.21
"9.0.64-154"
11.52.24
9.0.50
0.1.21
"0.1.22-42"
11.52.24
9.0.50
0.1.21

expected output:-

"11.54.24-95"
11.52.24
"9.0.64-154"
9.0.50
"0.1.22-42"
0.1.21

CodePudding user response:

Using a specialized tool like yq can help handling YAML with the shell:

yq eval-all '
    select(fi == 0) as $common |
    select(fi == 1) |                                
    .Tomcat.packages.OpenJDK11[0] = $common.openjdk11_version |
    .Tomcat.packages.Tomcat9[0] = $common.tomcat9_version |
    .Tomcat.packages.newrelic_infra[0] = $common.newrelic_infra_agent_version
' common.yml vars.yml
Tomcat:
  packages:
    OpenJDK11:
      - "11.54.24-95"
    Tomcat9:
      - "9.0.64-154"
    newrelic_infra:
      - "0.1.22-42"

CodePudding user response:

Figured this out

#!/bin/bash
declare -a arr=("openjdk11_version" "tomcat9_version" "newrelic_infra_agent_version")
declare -a brr=("OpenJDK11:" "Tomcat9:" "newrelic_infra:")
for ((i=0; i<${#arr[@]}; i  ))
do
   value=$(egrep "${arr[$i]}" common.yaml  | awk '{print $NF}' | uniq | cut -d '-' -f1 | tr -d '"')
   echo "$value"
   pakru=$(awk -v var=${brr[$i]} '$1 == "-"{ if (key == var) print $NF;next } {key=$1}' vars.yaml)
   echo "$pakru"
   sed -i "s/$pakru/$value/g" "vars.yaml"
done
  • Related