Complex variable

If I need the output as below, what syntax I should use. I use only korn shell.
=========In file ===========================

#!/usr/bin/ksn
P1=cat
P2=dog
P3=bat

for i 1 2 3
do
echo $P$i      # <---------- This line is the problem I face. What I should use.
done

========= End of file =======================
#Expected Result

cat
dog
bat

#Result

P1
P2
P3
eval echo '$'P$i 
1 Like

Try:

#!/usr/bin/ksh
P[1]=cat
P[2]=dog
P[3]=bat

for i in 1 2 3
do
  echo "${P}"      # <---------- This line is the problem I face. What I should use.
done
1 Like

Hello,

you can use array concept also in spite of using many variables as follows an example.

 
$ cat array.ksh

values="dog, cat, bat"
values_actual=`echo $values | sed 's/,//g'`
set -A array_values ${values_actual}
for i in ${array_values[@]}
do
echo $i
done
 
 
$ ksh array.ksh
dog
cat
bat
 
 

Hope this helps.

Thanks,
R. Singh

From the command line:-

Last login: Fri Jul  5 07:32:28 on ttys000
AMIGA:barrywalker~> ksh
AMIGA:uw> P[1]=Barry
AMIGA:uw> P[2]=Walker
AMIGA:uw> P[3]=G0LCU
AMIGA:uw> for i in 1 2 3; do; printf "${P}\n"; done   
Barry
Walker
G0LCU
AMIGA:uw> exit
AMIGA:barrywalker~> _
1 Like

Thank you very much. This is exactly I looking for.

Thank you very much. I jush know the shell script has arrry.

Thank you very much. The other technique to use array with stream editor.

Thank you very much. printf, Another new command I didn't know before combine with array.

It very kind of you all to suggest solutions to me. Thank you.