OscarAkaElvis
OscarAkaElvis

Reputation: 5714

bash. Best way to create a switched array (change keys for values)

I have an array:

declare -gA ifaces_and_macs
ifaces_and_macs["eth0"]="00:00:00:00:00:00"
ifaces_and_macs["eth1"]="00:00:00:00:00:11"

Desired array is:

ifaces_and_macs_switched["00:00:00:00:00:00"]="eth0"
ifaces_and_macs_switched["00:00:00:00:00:11"]="eth1"

I tried something like:

declare -gA ifaces_and_macs_switched
for iface_mac in "${ifaces_and_macs[@]}"; do
    ifaces_and_macs_switched["$iface_mac"]=${!ifaces_and_macs["$iface_mac"]}
done

What am I doing wrong? How can I get a switched array? Thank you.

Upvotes: 0

Views: 23

Answers (1)

Jean-François Fabre
Jean-François Fabre

Reputation: 140276

You have to iterate on the keys, not the values (once you get the value, you cannot get back to the keys!).

Then declare & build a dictionary with value as key of ifaces_and_macs, and using key as value of ifaces_and_macs

declare -gA ifaces_and_macs
declare -gA ifaces_and_macs_switched
ifaces_and_macs["eth0"]="00:00:00:00:00:00"
ifaces_and_macs["eth1"]="00:00:00:00:00:11"

for iface_mac in "${!ifaces_and_macs[@]}"; do
    ifaces_and_macs_switched[${ifaces_and_macs[$iface_mac]}]=$iface_mac 
done

echo ${ifaces_and_macs_switched["00:00:00:00:00:00"]}
echo ${ifaces_and_macs_switched["00:00:00:00:00:11"]}

result

eth0
eth1

Of course, that works well only if the values are unique (dictionary must be bijective): if there are duplicates in your values, you'll get only the last one.

Upvotes: 3

Related Questions