bashawksed

Awk to extract platformio.ini environments to a bash array


I'm trying to extract all the environments defined in a platformio.ini file so I can loop through them and perform some action before building. The file looks like:

; PlatformIO Project Configuration File

[env]
extra_scripts = pre:./somescript.py

[env:FirstEnvironment]
platform = atmelavr
board = nanoatmega328
framework = arduino

[env:SecondEnvironment]
platform = atmelavr
board = nanoatmega328
framework = arduino

I can manually do this

declare -a environments=(
"FirstEnvironment" 
"SecondEnvironment"
)
for i in "${environments[@]}"
do
    echo "$i"
done

But I now want to extract the information from the file. I've tried

awk '/\[env:.*\]/{print $0 }' platformio.ini

And it lists the environments but how can I create an array with that info? I've also seen readarray so maybe I could create an array with all the lines and then only execute if there is a match in a condition? I need to loop this twice so it would be cleaner to create the array only with the info I need.


Solution

  • Using bash + awk you can do this:

    readarray -t environments < <(
       awk -F 'env:' 'NF==2 {sub(/\]$/, ""); print $2}' file)
    
    # check content of array
    declare -p environments
    
    declare -a environments=([0]="FirstEnvironment" [1]="SecondEnvironment")
    

    Or else:

    for i in "${environments[@]}"; do
        echo "$i"
    done