Home > Enterprise >  How to replace string in a array using sed in shell script
How to replace string in a array using sed in shell script

Time:12-12

I have a array declared in a file and i want to replace/update array with latest values. below is the array saved in a file.

declare -A IMAGES_OVERRIDE
IMAGES_OVERRIDE=(
[service1]='gcr.io/test-project/image1:latest'
[service2]='gcr.io/test-project/image2:9.5.16'
[service3]='gcr.io/test-project/data/image3:latest'
)

Now I want to update service2 with latest image gcr.io/test-project/image2:10.0.1 and save into file.

I tried like below

sed -i 's/[service2]=.*/[service2]='gcr.io/test-project/image2:10.0.1'/' ./override

but I am getting below error.

sed: -e expression #1, char 35: unknown option to `s'

Same command is working me for other script but that is not array.

CodePudding user response:

Simply:

> sed -i "s#\[service2\]=.*#[service2]='gcr.io/test-project/image2:10.0.1'#" ./override
  • Notes:
  1. Use " instead of ' around sed expression (your sed script contains ');
  2. Use # instead of / to limit each part of sed replace expression (your new token contains /);
  3. Use \ before each [ and ] in RE expression ([ and ] are special RE characters);
  • Related