'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 1:[1]
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
Solution 2:[2]
With your shown samples and attempts, please try following awk code, written and tested in GNU awk.
readarray -t environments < <(
awk -v RS='(^|\n)\\[env:[^]]*\\](\n|$)' 'RT{gsub(/^\n|\n$|\n\[env:|\]\n/,"",RT);print RT}' Input_file)
# Get/print contents of array name environments here:
declare -p environments
##Output of printing array's elements will be:
declare -a environments=([0]="FirstEnvironment" [1]="SecondEnvironment")
Explanation: Simple explanation would be, running awk command(where setting RS to (^|\n)\\[env:[^]]*\\](\n|$) regex and in main block of program removing all thing and getting only needed/required output part from gsub in RT between [env: to till ] and its reading input from Input_file) and sending its output to readarray command to create bash array named environments. Then using declare -p command printing values of array along with its index items to show array's structure.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | anubhava |
| Solution 2 |
