Iterate over and replace element in array

The solution explained in the accepted answer to this similar question might be preferable:

array=("${array[@]/Apples/Canteloupe}")

This depends on your general attitude towards Bash trickery. In technical terms, there are no downsides to manually iterating over the elements.


In your original approach you are looping over the keys in the array using which you would not be able to get the index of that element to replace.

You need to change to modify the logic to loop over indices of the array as

for i in "${!copy[@]}"; do
    if [[ ${copy[$i]} == "Apples" ]]; then
        copy[$i]="Canteloupe"
    fi
done

should solve your problem.

The construct for i in "${!copy[@]}"; do is for looping with indices of the array starting from 0 to size of the array which lets you to replace the element in the index where you find the required string.


Expanding the answer to point out the difference when using either of array iteration ways.

Looping over indices

for i in "${!copy[@]}"; do 
  printf "%s\t%s\n" "$i" "${copy[$i]}"
done

prints

0       Oranges
1       Apples
2       Bananas
3       Grapes

and over keys

for i in "${copy[@]}"; do 
  printf "%s\n" "$i"
done

produces,

Oranges
Apples
Bananas
Grapes

Tags:

Bash