Bash – How to Store Function Output into an Array

bashshell-scripttext processing

DATA SET file name "demo.txt"

ID|SAL|COL|PER|TAG|GER
1"|"1.11"|"2.22"|"1.1"|"2.2"|D"
2"|"1.234"|"3.234"|"2.2222"|"2.34"|"B"
3"|"1.234"|"35.23"|"3.2"|"2.34"|"A"

I have created a function which will automatically calculate decimal column sum below is the function
I am calling that function in main.sh script

demo()
{
FILE_NAME="$1"
COLUMN_NAME="$2"

alpha=( $(awk -F"|" 'NR==1{for(i=1;i<=NF;i++){if ($i ~ /'$COLUMN_NAME'/){print i;}}}' $FILE_NAME) )

for each in "${alpha[@]}"
do
   awk -F'"?\\|"?' '{T+=$('$each')} END { printf "%.2f\n", T }' $FILE_NAME  
done

}

Script : main.sh

#function called in main.sh script

demo demo.txt 'SAL|COL|PER|TAG'

issue is how do i get the output into an array

below is the output i am getting need to store into array1

3.57 40.68 6.52 6.88

second array is this below output getting from another program

array2={3.57 40.68 6.52 6.88}

**so that I can match the array1 with array 2 position value

array1[0] with array2[0] 
array1[1] with array2[1] 
array1[2] with array2[2] 
array1[3] with array2[3] 

if all succeed should display success status as YES

i have solution which is partially working … help me with some solution
so that i can store each value of an array to array1

FILE_NAME="$1"
COLUMN_NAME="$2"

alpha=( $(awk -F"|" 'NR==1{for(i=1;i<=NF;i++){if ($i ~ /'$COLUMN_NAME'/){print i;}}}' $FILE_NAME) )

declare -a array=();

for each in "${alpha[@]}"
do
        #var=($(awk -F'"?\\|"?' '{T+=$('$each')} END { printf "%.2f\n", T }' $FILE_NAME))
        mapfile -t array <<< "$(awk -F'"?\\|"?' '{T+=$('$each')} END { printf "%.2f\n", T }' $FILE_NAME)"
        #awk -F'"?\\|"?' '{T+=$('$each')} END { printf "%.2f\n", T }' $FILE_NAME
done

echo "${array[@]}"

Best Answer

The problem with your partly working solution is you store the single value from the sum of one column into the entire array every time, which deletes the previous values.

The solution is to stuff the values into the array one by one, rather than using the mapfile command which requires all the values on one input line:

FILE_NAME="$1"
COLUMN_NAME="$2"

alpha=( $(awk -F"|" 'NR==1{for(i=1;i<=NF;i++){if ($i ~ /'$COLUMN_NAME'/){print i;}}}' $FILE_NAME) )

declare -a array=()

n=0

for each in "${alpha[@]}"
do
        array[n]="$(awk -F'"?\\|"?' '{T+=$('$each')} END { printf "%.2f\n", T }' $FILE_NAME)"
        ((n=n+1))
done

echo "${array[@]}"

Running this gives:

$ bash test.sh demo.txt 'SAL|COL|PER|TAG'
3.58 40.68 6.52 6.88
Related Question