using an awk internal variable as parameter for an external array

Hello,

I am running a bash script under linux which first defines an CA-array like

j=0
num1=120.00
num2=10.00
until [$j -gt 5 ]
do
  CA[$j]='echo $num1 + $j*$num2'
  j=$[$j+1]
done
 

within the later awk section of this same script I want to read data from a file. If the value of the second column is equal to the value of CA[0 to 5] the array MF[0 to 5] should read the value from column 59:

awk '
BEGIN {
  ...
  i=0
  while ( i<5 ) {
    if ( match($2,/^'${CA[1]}'/) ) { MF = $59 }
      i = i + 1
  }
}
END ' ${FILE}
 

As long in the bold written part the parameter of the array is fixed to certain value (here "1") the script works fine. In later stage I do want to read dozend of lines from the file and not only 5!

Does anyone know how I do have to change the script ('${CA[1]}') in order to have "i" of the awk loop to define the parameter fo the external array CA? Any help or work arround is appreciated.

Regards,

MotAah

No way - there are no two-way communications between syntax constructions of shell and awk (like you want).
You can use a scalar variable with embeded newlines. Send its value to awk through -v option and split it in the BEGIN block to an awk array. Or use a temp file.

1 Like

An easy way to generate a string of "thing1 thing2 thing3 ..." from an array using any separator you want is:

OLDIFS="$IFS"
IFS="|" # adjust to whatever you want
LIST="${ARR[*]}"
IFS="${OLDIFS}"

awk -v LIST="$LIST" 'BEGIN { split(LIST, A, "|"); } ....

which will turn the array ARR=( 1 2 3 ) into LIST="1|2|3" for easy feeding into awk, which splits it on the same separator, into the awk array A.

1 Like

Hi,

thank you for the quick reply. I am using the list option now which transfers the array into the awk script well. I might try the temp-file option as well as I currently running into a format problem. But that is another problem.

Thanks again for your help

MotAah