How to use `yq` to select key-value pairs and format them into "$key=$value" style outputs?

Viewed 867

Let say I have YAML file that looks like this:

FOO: somefoo
BAR: somebar

I would like to convert this (using yq) into the following so that I can source the contents into environment variables:

export BAR='somebar'
export FOO='somefoo'

I can do it it with jq by converting the input to JSON first, but I can't seem to figure out how to do it with yq only. (I am using yq 4.x, <4.18).

So, concretely, how could I do the following using just yq?

INPUT="FOO: somefoo
BAR: somebar"

echo "$INPUT" | yq e 'to_json' - | jq -r 'keys[] as $k | "export \($k)='\''\(.[$k])'\''"'
2 Answers

You could switch to kislyuk's yq which uses native jq under the hood. Then, you would just need to_entries to access key and value, string interpolation in combination with the -r flag to produce the output, and @sh to escape for shell compliance:

yq -r 'to_entries[] | "export \(.key)=\(.value | @sh)"'
export FOO='somefoo'
export BAR='somebar'

Use the key operator and string concatenation:

$ echo "$INPUT" | yq $'.[] | "export " + key + "=\'" + . + "\'"'
export FOO='somefoo'
export BAR='somebar'

Tested with yq 4.27.2

Related