Extract keys from yaml file using awk
Matthew Harrington
Let's say I have a yaml file like this one:
foo: bar: 1
env: firstVar: true secondVar: 20 aa_thirdVar: 'hello' aa_fourthVar: falseand 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.
1 Answer
Using the yq command from the a proper tool to parse the YAML format files, you could do:
yq -r '.env|to_entries[]| if (.key|test("^[^a][^a][^_]*$")) then ( .key + "=" + (.value | @sh) ) else empty end
' infilewhich outputs:
firstVar=true
secondVar=20now you only need to export these sets of variables
export $(yq ... )or create an array:
IFS=$'\n' arr=( $(yq ... ) )In the ( .key + "=" + (.value | @sh) ) part, it concatenates the pairs of the key-value that those are produced by using the to_entries function and the @sh syntax (which is known as the "Format String and Escaping") is used to provide the POSIX sh shell escape formatting on values.