0

Usual arrays are looped over using the indices. For my application I need to use an independent variable to extract values from array.

#!/bin/bash
# Author : Ankit
echo "Please enter the number of files (max index number of file): "
read iv
fname="t3p_"
echo "You entered: $iv, $fname" ;
#---------------------------------------------------------------------------------------------
#Reference values
refxa=(2.0 3.0 4.0)
refza=(1.0 6.0 7.0)
#---------------------------------------------------------------------------------------------
rm result.txt
#echo  $iv,$fname
i=1
while [ $i -lt $(($iv+1)) ] ;  do
xxn=5
zzn=19
refxn=$(echo $refxa | awk '{print $i}')
refzn=$(echo $refza | awk '{print $i}')

delta_x=`echo $xxn - $refxn  | bc -l`
delta_z=`echo $zzn - $refzn  | bc -l`

printf "%f\t%f\t%f\t%f\t%f\n" "$i" "$xxn" "$delta_x" "$zzn" "$delta_z" >>  result.txt

i=$[$i+1]
done
echo -e  "------------------------------------------------------------------------------------"
cat result.txt

My question :

  1. As seen above I want to subtract value xxn from ith array element($i) which is the index of the loop. How to access the array element using the variable $i. (Using array index is not an option since in my script $i is related to several other parameters and that code is not shown here.)

I tried ${refxa[i]} which did not work.

Expected output (3rd and 5th column are xxn-refxn[i] and zzn-refzn[i]:

You entered: 3, t3p_
------------------------------------------------------------------------------------
1.000000        5.000000        3.000000        19.000000       18.000000
2.000000        5.000000        2.000000        19.000000       13.000000
3.000000        5.000000        1.000000        19.000000       12.000000
8
  • Please provide desired / expected output. Commented Apr 21, 2017 at 7:41
  • You know that ${refxa[i]} is not valid and it has to be ${refxa[$i]}, right? Commented Apr 21, 2017 at 8:21
  • The answer in this question (stackoverflow.com/questions/11856132/…) does not work in my case and I don't know why. Commented Apr 21, 2017 at 8:22
  • 1
    Hm... you said: ith array element($i) which is the index ... later Using array index is not an option ... bogus. Anyway - in bash the arrays has zero-based indexing - e.g. the first element is ${arr[0]}. Commented Apr 21, 2017 at 8:23
  • 1
    @jm666 We learnt something new today. Your sample code works ok , thanks. Commented Apr 21, 2017 at 8:34

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.