Search code examples
arraysbashyamlyq

How to strip characters (in this case dashes "-") from YAML arrays using yq


Say I have a YAML array and I want to read the items into a bash array:

yaml='- this - is - a - yaml - array'
declare -a arr;
readarray -t arr < <(echo "$yaml" | yq -r '.');
echo ${arr[@]}

The bash array entries retain the - symbols.

How might I strip out the - symbols using yq?


Using Mike Farrah's yq (v4.31.2) but interested in answers for Andrey Kislyuk's too.


Solution

  • yaml='- this - is - a - yaml - array'
    

    I suspect this isn't what you think it is in yaml. This is an array with a single element string with the value "this - is - a - yaml - array".

    You need newline characters between each element.

    The "-" is being printed because yq is printing the array yaml node rather than the child elements individually. You just need to splat the results:

    echo "- this\n- is\n- a\n- yaml\n- array" | yq '.[]'
    
    this
    is
    a
    yaml
    array
    

    disclaimer: I wrote yq