2

I am trying to print a filename which contains decimal point numbers... say

 L2.3stop.txt

I have variables defined as :

 z1=2.3
 z2=3.4
 z3=7.8
 z4=8.9

and so on

In a for loop i runs from 1 to 5

Inside the loop if I do

 temp=`echo z$i`

and then I print the file name using

 echo L${temp}stop.txt

it just prints

 Lz1stop.txt
 Lz2stop.txt

etc..

How can I print the desired filename....

I also tried using

 echo L$((z$i))stop.txt

but this only works when z1, z2, z3 etc are integers and not floating numbers....

PyariBilli
  • 501
  • 1
  • 7
  • 17
  • 3
    Did you know that Bash has [arrays](http://tldp.org/LDP/abs/html/arrays.html)? – Mat May 21 '13 at 20:04

4 Answers4

4

I hope this helps:

z1=2.3
z2=3.4
z3=7.8
z4=8.9

for i in {1..4};do
        echo L$(eval "echo \$z"$i)stop.txt
done

or this should work too:

for i in {1..4};do
    echo L$(echo $(echo "\$z$i"))stop.txt
done

outputs:

L2.3stop.txt
L3.4stop.txt
L7.8stop.txt
L8.9stop.txt
Kent
  • 189,393
  • 32
  • 233
  • 301
2

This is not portable, but in bash you can do:

name=z$i
echo ${!name}
William Pursell
  • 204,365
  • 48
  • 270
  • 300
2

Best (using an array):

z=( 2.3 3.4 7.8 8.9 9.8 ) # Added fifth value
for x in "${z[@]}"
do
    echo L${x}stop.txt
done

Less good (using indirect expansion — a bash feature):

z1=2.3
z2=3.4
z3=7.8
z4=8.9
z5=9.8  # Added fifth value

for i in {1..5}
do
    v=z$i
    echo L${!v}stop.txt
done

Both produce:

L2.3stop.txt
L3.4stop.txt
L7.8stop.txt
L8.9stop.txt
L9.8stop.txt

Both avoid using eval which is not too harmful in this context but is dangerous (and difficult to use correctly) in general.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
2

If you have defined variable z, you can do this:

for v in ${!z*}; do echo L${!v}stop.txt; done

or:

for v in z{1..4}; do echo L${!v}stop.txt; done
Stephen Rauch
  • 47,830
  • 31
  • 106
  • 135
jack
  • 21
  • 2