0

Inside a loop I have a variable to be used for the calculation, using bc, of another variable. However, the result I get is totally incorrect. I have 32 files, named test0, test1 and so on. My script reads as follow:

for i in {0..31}; do
  declare x$i=$(wc -l < test$i)
  declare y$i=$(echo $x$i/10 | bc) 
done

for the variable x, I get the good results, i.e. each x$istores the number of lines of the correspondent test$i. Then I'd like to simple know how much is 10% of each x$i and stores it in variables y$i. And, as I said above, I get completely wrong results using that script. For example, for x0=155287510 I got y0=20.

tripleee
  • 175,061
  • 34
  • 275
  • 318
ziulfer
  • 1,339
  • 5
  • 18
  • 30

1 Answers1

6

The problem is that $x$i is not the value of a variable named x$i but the catenation of the values of the variables x and i.

You could convert your script to use Bash arrays easily, but it seems like you would be better off doing this in Awk.

declare -a x
declare -a y
for i in {0..31}; do
  x[$i]=$(wc -l < test$i)
  y[$i]=$(echo "${x[$i]}"/10 | bc) 
done

If you just want the result from the calculation,

wc -l test[0-9] test[12][0-9] test3[01] |
awk '{$1 /= 10 }1'
tripleee
  • 175,061
  • 34
  • 275
  • 318
  • I don't think its even worth spawning `bc` every loop iteration, when the shell will happily divide by 10 itself `y[$i]=$(( ${x[$i]} / 10 ))`. (Of course `bc` is more useful if decimal results are required.) – Digital Trauma Sep 23 '14 at 18:01
  • Or if you don't care about rounding, simply drop the last digit -- `${x[$i]%?}` – tripleee Sep 25 '14 at 03:14
  • I considered that but it would result on an empty string for 1-digit numbers – Digital Trauma Sep 25 '14 at 03:16