0

Let's say I have a yaml file like this one:

env:
 firstVar: true
 secondVar: 20
 aa_thirdVar: 'hello'
 aa_fourthVar: false

and I need to get the keys under the env key except for the keys with aa_ prefix as a bash array in order to use the array in a bash script. I need to do this using standard Linux tools like sed, awk etc. without external dependencies. How can accomplish that?

Sergey
  • 1,000
  • 8
  • 19
  • Unfortunately no, this answer is more general. I explored available questions/answers before posting mine. – Sergey Jan 28 '22 at 22:04
  • what would be the resulting array? `([firstvar]="true" [secondVar]="20")`? – Fravadona Jan 28 '22 at 23:28
  • The resulting array is supposed to contain only keys without the `aa_` prefix like ARR=(firstVar, secondVar). – Sergey Jan 29 '22 at 09:40

2 Answers2

1

The first thing is produce key=value pairs.

You can use ruby with the built in yaml parser:

ruby -r yaml -e 'data=YAML.load($<.read)
data["env"].
    select{|k,v| k.to_s.match(/^(?!aa)/)}.
    each{|k,v| puts "#{k}=#{v}"}
' file

Or, more fragile, you could use this awk:

awk '
/^env:/{con=$1; next}
$1~/aa_/{next}
con=="env" 
{sub(/:$/,"",$1); print $1 "=" $2}' file

Either of those prints:

firstVar=true
secondVar=20 

Now have a Bash loop that will add key=value type pairs to an associative array aa like so:

declare -A aa
while IFS="=" read -r k v; do
    echo "$k $v"
    aa["$k"]="$v"
done < <(ruby -r yaml -e 'data=YAML.load($<.read)
data["env"].
    select{|k,v| k.to_s.match(/^(?!aa)/)}.
    each{|k,v| puts "#{k}=#{v}"}
' file)

Result:

declare -p aa

Prints:

declare -A aa=([firstVar]="true" [secondVar]="20" )
dawg
  • 98,345
  • 23
  • 131
  • 206
0

i use yq that is wrapper for jq tool https://github.com/kislyuk/yq

David
  • 302
  • 1
  • 4