Accessing value in KV pair during loop

Viewed 67

I have an associative array where both the key and the value are xml strings. I'm using this for a find/replace operation in a bash script.

#!/usr/local/bin/bash
declare -A findReplace

findReplace['<item name="Alice" title="President"/>']='<item name Bob title="CEO"/>'

for e in "${findReplace[@]}"; do
  find="$e"
  replace="${findReplace[$e]}"
  printf "\tSearching for: ${find}\n"
  printf "\tReplacing with: "${replace}"\n"
done

This is the output of this:

Searching for: <item name Bob title="CEO"/>
Replacing with:

See how the value doesn't read in correctly? I've tried iterating with an index and using that index to pull in both, but then both the key and the value only read up to the space.

Hopefully this is clear. Thanks.

1 Answers

Add ! to iterate over the array's keys rather than its values. Also, avoid substituting variables directly into printf's format string. Use %s and pass the variables as separate arguments.

for e in "${!findReplace[@]}"; do
  find="$e"
  replace="${findReplace[$e]}"
  printf '\tSearching for: %s\n' "${find}"
  printf '\tReplacing with: %s\n' "${replace}"
done
Related