homeGrown homeGrown - 5 years ago 326
Bash Question

Iterating over associative array in bash

I am renaming strings recursively using an associative array. Th array part is working, when I echo

$index
&
${code_names[$index]}
they print correctly. However the files are not modified. When I run the
find | sed
command in the shell it works however inside a bash script it doesnt.

Update

Also script runs ok if I just hardcode the string to be renamed:
find . -name $file_type -print0 | xargs -0 sed -i 's/TEST/BAT/g'


#!/usr/bin/env bash
dir=$(pwd)
base=$dir"/../../new/repo"
file_type="*Kconfig"
cd $base

declare -A code_names
code_names[TEST]=BAT
code_names[FUGT]=BLANK

for index in "${!code_names[@]}"
do
find . -name $file_type -print0 | xargs -0 sed -i 's/$index/${code_names[$index]}/g'
done

Answer Source

The bare variable $file_type gets expanded by the shell. Double quote it. Variables are not expanded in single quotes, use double quotes instead. Note that it can break if $index or ${code_names[$index]} contain characters with special meaning for sed (like /).

find . -name "$file_type" -print0 \
| xargs -0 sed -i "s/$index/${code_names[$index]}/g"
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download