Variable substitution with arrays


 
Thread Tools Search this Thread
Top Forums Shell Programming and Scripting Variable substitution with arrays
# 15  
Old 09-14-2017
Bakunin: My apologies for the late reply!

Your solution looks very promising Smilie

I played with it a little bit to get the hang of it.

I hit a roadblock as soon as I replaced "1 2 3 4 5" in the nested for loop with "animals fruits drinks cities countries". I tried it in 2 ways but got the same result in both attempts. I also tried putting

Code:
typeset array[animals]="dog cat horse penguin cow"
typeset array[fruits]="orange apple grapes peach mango"
typeset array[drinks]="juice milk coffee tea coke"
typeset array[cities]="toronto paris london glasgow sydney"
typeset array[countries]="canada france england scotland australia"
all=(animals fruits drinks cities countries)

typeset -i i=1
typeset -i j=1

printf 'Output 1\n\n';
# display column-wise
for i in 1 2 3 4 5; do
     for j in animals fruits drinks cities countries; do
          echo "${array[${j}]}" | cut -d' ' -f $i
     done
done

printf '\n\nOutput 2\n\n';

# display column-wise
for i in 1 2 3 4 5; do
     for j in "${all[@]}" ; do
          echo "${array[${j}]}" | cut -d' ' -f $i
     done
done

Code:
abc@xyz$ ./typeset.sh
Output 1

canada
canada
canada
canada
canada
france
france
france
france
france
england
england
england
england
england
scotland
scotland
scotland
scotland
scotland
australia
australia
australia
australia
australia


Output 2

canada
canada
canada
canada
canada
france
france
france
france
france
england
england
england
england
england
scotland
scotland
scotland
scotland
scotland
australia
australia
australia
australia
australia

I had also tried the following and still got the same results:

Code:
typeset array['animals']="dog cat horse penguin cow"
typeset array['fruits']="orange apple grapes peach mango"
typeset array['drinks']="juice milk coffee tea coke"
typeset array['cities']="toronto paris london glasgow sydney"
typeset array['countries']="canada france england scotland australia"
all=('animals' 'fruits' 'drinks' 'cities' 'countries')


At least this alternative works just fine:


Code:
typeset array[1]="dog cat horse penguin cow"
typeset array[2]="orange apple grapes peach mango"
typeset array[3]="juice milk coffee tea coke"
typeset array[4]="toronto paris london glasgow sydney"
typeset array[5]="canada france england scotland australia"
all=(1 2 3 4 5)

# display column-wise
for i in 1 2 3 4 5; do 
     for j in "${all[@]}"; do 
          echo "${array[$j]}" | cut -d' ' -f $i
     done
done

abc@xyz$ ./typeset.sh
dog
orange
juice
toronto
canada
cat
apple
milk
paris
france
horse
grapes
coffee
london
england
penguin
peach
tea
glasgow
scotland
cow
mango
coke
sydney
australia

Is there a way to make it work with all=(animals fruits drinks cities countries) ?
# 16  
Old 09-15-2017
Quote:
Originally Posted by Kingzy
I hit a roadblock as soon as I replaced "1 2 3 4 5" in the nested for loop with "animals fruits drinks cities countries".
I hate to say it, but: this was to be expected. What you tried was a so-called "associative array". This is an array where the index is not numbers but (arbitrary) strings. There some programming languages which offer this kind of arrays (awk, for instance), but not bash. You can use ksh93 (Korn shell in its '93 version), which does offer such a functionality, but not bash or ksh88.

Quote:
Originally Posted by Kingzy
Is there a way to make it work with all=(animals fruits drinks cities countries) ?
Lets see. I warn you beforehand, this is more a workaround, not really a solution. Consider the following sample script:

Code:
#! /bin/bash

typeset -i animals=1
typeset -i fruits=2
typeset -i drinks=3
typeset -i cities=4
typeset -i countries=5
typeset    all=($animals $fruits $drinks $cities $countries) 

typeset arr[$animals]="dog cat horse penguin cow"
typeset arr[$fruits]="orange apple grapes peach mango"
typeset arr[$drinks]="juice milk coffee tea coke"
typeset arr[$cities]="toronto paris london glasgow sydney"
typeset arr[$countries]="canada france england scotland australia"

for i in ${all[@]} ; do
     for j in 1 2 3 4 5 ; do
          echo ${i}:${j} $(echo ${arr[$i]} | cut -d' ' -f$j)
     done
done

exit 0

I hope this helps.

bakunin
This User Gave Thanks to bakunin For This Post:
# 17  
Old 09-15-2017
Quote:
Originally Posted by bakunin
I hate to say it, but: this was to be expected. What you tried was a so-called "associative array". This is an array where the index is not numbers but (arbitrary) strings. There some programming languages which offer this kind of arrays (awk, for instance), but not bash.
.
.
.
As much as I hate to say it: ever since version 4 (which the OP seems to run), bash HAS associative arrays:

man bash:
Quote:
Arrays
Bash provides one-dimensional indexed and associative array variables.
.
.
.
Associative arrays are created using declare -A name.
You need to declare / typeset them correctly, though ...

Code:
typeset -A arr=([animals]="dog cat horse penguin cow" [fruits]="orange apple grapes peach mango" [drinks]="juice milk coffee tea coke" [cities]="toronto paris london glasgow sydney" [countries]="canada france england scotland australia")
for i in ${!arr[@]}
  do    echo $i
        TMP=(${arr[$i]})
        for j in ${!TMP[@]}
          do    echo "  " ${TMP[$j]}
          done
  done
animals
     dog
     cat
     horse
     penguin
     cow
drinks
     juice
     milk
     coffee
     tea
     coke
fruits
     orange
     apple
     grapes
     peach
     mango
countries
     canada
     france
     england
     scotland
     australia
cities
     toronto
     paris
     london
     glasgow
     sydney


Last edited by RudiC; 09-15-2017 at 10:32 AM..
These 2 Users Gave Thanks to RudiC For This Post:
# 18  
Old 09-15-2017
Quote:
Originally Posted by RudiC
ever since version 4 (which the OP seems to run), bash HAS associative arrays:
Oh! I stand corrected - thanks for pointing that out.

bakunin
# 19  
Old 09-23-2017
Thanks a lot RudiC!

I've been spending some time trying to have a column-wise output, as opposed to row-wise as in your example, but most importantly target specific items in each "array" as well. All while typesetting everything the way you did. Here is what I came up with:

Code:
typeset -A arr=(

[animals]="dog cat horse penguin cow" 
[fruits]="orange apple grapes peach mango" 
[drinks]="juice milk coffee tea coke" 
[cities]="toronto paris london glasgow sydney" 
[countries]="canada france england scotland australia"

)

declare all=(animals fruits drinks cities countries)

j=0
k=2
for i in ${!arr[@]}
  do
        TMP=(${arr[$i]})
        echo ${all[j]} "  ->  " ${TMP[k]}
        (( j++ ))
  done

Here I hardcoded k but I do have a way in my actual script to increment it. As per the output below, I am getting the 2nd item of each array as expected but their order is somehow incorrect Smilie

Code:
abc@xyz$ ./loop.sh
animals   ->   coffee
fruits   ->   grapes
drinks   ->   london
cities   ->   horse
countries   ->   england

k=3 outputs the same [incorrect] pattern:

Code:
abc@xyz./loop.sh
animals   ->   tea
fruits   ->   peach
drinks   ->   glasgow
cities   ->   penguin
countries   ->   scotland

Quote:
Lets see. I warn you beforehand, this is more a workaround, not really a solution. Consider the following sample script:
Bakunin: Thank you as well! But why is it "not really a solution"? Smilie

As with RudiC's solution, I'm outputting column-wise and hardcoded $y to target a specific index, but this time the order is correct:

Code:
#! /bin/bash

typeset -i animals=1
typeset -i fruits=2
typeset -i drinks=3
typeset -i cities=4
typeset -i countries=5
typeset    all=($animals $fruits $drinks $cities $countries) 

typeset arr[$animals]="dog cat horse penguin cow"
typeset arr[$fruits]="orange apple grapes peach mango"
typeset arr[$drinks]="juice milk coffee tea coke"
typeset arr[$cities]="toronto paris london glasgow sydney"
typeset arr[$countries]="canada france england scotland australia"

for j in {1..5} ; do
  for i in ${all[@]} ; do
          echo ${i}:${j} $(echo ${arr[$i]} | cut -d' ' -f$j)
     done
done

printf "\n";
printf "Customized\n";
printf "\n";

y=2
z=`expr $y + 1`
for i in ${all[@]} ; do
    echo ${i}:$y $(echo ${arr[$i]} | cut -d' ' -f$z)
done

exit 0

abc@xyz./loop2.sh
1:1 dog
2:1 orange
3:1 juice
4:1 toronto
5:1 canada
1:2 cat
2:2 apple
3:2 milk
4:2 paris
5:2 france
1:3 horse
2:3 grapes
3:3 coffee
4:3 london
5:3 england
1:4 penguin
2:4 peach
3:4 tea
4:4 glasgow
5:4 scotland
1:5 cow
2:5 mango
3:5 coke
4:5 sydney
5:5 australia

Customized

1:2 horse
2:2 grapes
3:2 coffee
4:2 london
5:2 england

Code:
As much as I hate to say it: ever since version 4 (which the OP seems to run), bash HAS associative arrays:

Yes I'm using version 4 both at home and work, though I don't have the luxury of using typeset -n at work.

---------- Post updated at 05:55 PM ---------- Previous update was at 02:15 PM ----------

I fixed the order! I just had to change the for loop Smilie


Code:
typeset -A arr=(
  [animals]="dog cat horse penguin cow" 
  [fruits]="orange apple grapes peach mango" 
  [drinks]="juice milk coffee tea coke" 
  [cities]="toronto paris london glasgow sydney" 
  [countries]="canada france england scotland australia"
)
declare all=(animals fruits drinks cities countries)

j=0
k=4
for i in ${all[@]}
  do
        TMP=(${arr[$i]})
        echo ${all[j]} "  ->  " ${TMP[k]}
        (( j++ ))
  done

abc@xyz$ ./loop.sh
animals   ->   cow
fruits   ->   mango
drinks   ->   coke
cities   ->   sydney
countries   ->   australia


Last edited by Kingzy; 09-23-2017 at 03:28 PM..
Login or Register to Ask a Question

Previous Thread | Next Thread

10 More Discussions You Might Find Interesting

1. Shell Programming and Scripting

Variable substitution

Hi, I have to write a shell script in which I have to substitute a variable within a variable. For example, var1=aaa var2=file.$var1.txt The output should be, echo $var2 file.aaa.txt Can someone please help me in getting this. I tried using eval, but it didnt work. I might be using it... (2 Replies)
Discussion started by: grajp002
2 Replies

2. Shell Programming and Scripting

How to use variable with command substitution in variable

For example I have variable like below echo $OUTPUT /some/path/`uname -n` when I try to use the variable OUTPUT like below cd $OUTPUT or cd ${OUTPUT} I am getting bad substituion error message $ cd $OUTPUT ksh: cd: bad substitution $ cd ${OUTPUT} ksh: cd: bad substitution ... (1 Reply)
Discussion started by: rajukv
1 Replies

3. Shell Programming and Scripting

Variable Substitution

Hi , I have a variable as follows, Temp=`cat ABC.txt | cut -c5-` This will yeild a part of the date. say , 200912. I would like to substitute this variable's value in a filename. eg: File200912F.zip when i say File$TempF.zip , it is not substituting. Any help ? Thanks in... (2 Replies)
Discussion started by: mohanpadamata
2 Replies

4. Shell Programming and Scripting

bash: combine arrays with weird substitution/references

Hi all. I'm trying to finish a bash script with the following elements: ARRAY="blah $ITEM blah blah" ARRAY="blah blah $ITEM blah bluh" #ARRAY="...." # ...the ARRAY elements represent a variable but defined # syntax and they're all hard-coded in the script. #(...) ITEMS='1.0 2.3... (2 Replies)
Discussion started by: yomaya
2 Replies

5. Shell Programming and Scripting

variable substitution

file1.ksh #!/bin/ksh test5_create="I am a man" # test5 will be dynamic and the value will be passed from command line a=${1}_create echo $a # i need the output as "I am a man" ./file1.ksh test5 # i run the script like this any suggessions guys... (1 Reply)
Discussion started by: giri_luck
1 Replies

6. UNIX for Dummies Questions & Answers

Variable substitution

Hi, That might be pretty simple. How can I generate a variable name and get their value ? Thanks a lot. Something like: >CUSTOMER_NF=26 > object=CUSTOMER > echo ${object}_NF CUSTOMER_NF > echo ${${object}_NF} ksh: ${${object}_NF}: 0403-011 The specified substitution is... (7 Replies)
Discussion started by: Leo_NN
7 Replies

7. Shell Programming and Scripting

Sed variable substitution when variable constructed of a directory path

Hello, i have another sed question.. I'm trying to do variable substition with sed and i'm running into a problem. my var1 is a string constructed like this: filename1 filerev1 filepath1 my var2 is another string constructed like this: filename2 filerev2 filepath2 when i do... (2 Replies)
Discussion started by: alrinno
2 Replies

8. Shell Programming and Scripting

Variable Substitution

I have run into a wall with my iptables firewall scripting. I am blocking all of the private side IP addresses on the WAN interface on systems running NAT. However, if the system is not running NAT and needs to allow access to the local LAN on the WAN interface, I need to block all but one of... (2 Replies)
Discussion started by: garak
2 Replies

9. UNIX for Dummies Questions & Answers

variable substitution

Hi everyone, I have a simple question to ask : In a script that I'm writting, I need to create variables on-the-fly. For instance, for every iterartion of the following loop a var_X variable should be generated : #!/bin/ksh a="1 2 3" for i in $a do var_${i}=$i echo "${var_$i}" done ... (1 Reply)
Discussion started by: ck-18
1 Replies

10. UNIX for Advanced & Expert Users

Substitution in a variable

Hey All, I'm trying to clean up a variable using sed but It dosn't seem to work. I'm trying to find all the spaces and replace them with "\ " (a slash and a space). For Example "Hello World" should become "Hello\ World". But it does nothing. If I put it directly into the command line it works... (3 Replies)
Discussion started by: spragueg
3 Replies
Login or Register to Ask a Question