Velvet Star Monitor

Standout celebrity highlights with iconic style.

updates

Extract keys from yaml file using awk

Writer 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: 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.

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
' infile

which outputs:

firstVar=true
secondVar=20

now 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.

3

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy