JudeC
JudeC

Reputation: 1

How to retrieve the value from an array table in Bash

I created an array table but want to retrieve the second value based on the first value.

For the below table, basically I want to have if animal is cow, show me "moo"; if it's dinosaur, show me "roar"...

ARRAY=( "cow:moo"
        "dinosaur:roar"
        "bird:chirp"
        "bash:rock" )

Upvotes: 0

Views: 53

Answers (2)

Paul Hodges
Paul Hodges

Reputation: 15273

You might also want to refactor and use parallel arrays.

animal=( cow dinosaur bird )
sound=( moo road chirp )
for ndx in "${!animal[@]}"
do echo "${animal[ndx]}: ${sound[ndx]}"
done
cow: moo
dinosaur: road
bird: chirp

Or as chepner said, use an associative array -

declare -A sound=(
   [cow]=moo
   [dinosaur]=roar
   [bird]=chirp
)
for critter in "${!sound[@]}"
do echo "$critter: ${sound[$critter]}"
done  # note that these will be unordered
dinosaur: roar
cow: moo
bird: chirp

I'd use the associative.

Upvotes: 0

chepner
chepner

Reputation: 531055

Use an associative array instead.

$ declare -A array
$ array=([cow]=moo [dinosaur]=roar [bird]=chirp [bash]=rock)
$ echo "${array[cow]}"
moo

You can generate the above from your original automatically:

old_array=( "cow:moo" "dinosaur:roar" "bird:chirp" "bash:rock" )
declare -A array
for x in "${old_array[@]}"; do
  IFS=: read key value <<< "$x"
  # Or
  # key=${x%%:*}
  # value=${x#*:}
  array[$key]=$value
done

Upvotes: 2

Related Questions