Monday, January 31, 2022

[SOLVED] How do I add different variables to an AWK result which is showing in array?

Issue

I have this output from awk:

vfp-10m1
vfp-8m1
vfp-9m1
vfp-10m2
vfp-8m2
vfp-9m2
vfp-10vr
vfp-8vr
vfp-9vr

How can I do so each line has its unique variable? like A=vfp-8m1 and B=vfp-8m2 , so on and so forth?


Solution

For demo purposes:

$ cat awk.out
vfp-10m1
vfp-8m1
vfp-9m1
vfp-10m2
vfp-8m2
vfp-9m2
vfp-10vr
vfp-8vr
vfp-9vr

One idea using mapfile to load the awk output into an array named vars[]:

mapfile -t vars < awk.out

# NOTE: feeding directly from a `awk` script:

mapfile -t vars < <(awk '1' awk.out)

Array contents:

$ typeset -p vars
declare -a vars=([0]="vfp-10m1" [1]="vfp-8m1" [2]="vfp-9m1" [3]="vfp-10m2" [4]="vfp-8m2" [5]="vfp-9m2" [6]="vfp-10vr" [7]="vfp-8vr" [8]="vfp-9vr")

Accessing via a loop:

for i in "${!vars[@]}"
do
    echo "index=$i ; value=${vars[i]}"
done

Which generates:

index=0 ; value=vfp-10m1
index=1 ; value=vfp-8m1
index=2 ; value=vfp-9m1
index=3 ; value=vfp-10m2
index=4 ; value=vfp-8m2
index=5 ; value=vfp-9m2
index=6 ; value=vfp-10vr
index=7 ; value=vfp-8vr
index=8 ; value=vfp-9vr


Answered By - markp-fuso
Answer Checked By - Terry (WPSolving Volunteer)