简体   繁体   English

如何在 shell 脚本中使用 sed 替换数组中的字符串

[英]How to replace string in a array using sed in shell script

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.现在我想用最新的图像 gcr.io/test-project/image2:10.0.1 更新 service2 并保存到文件中。

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.相同的命令正在为其他脚本工作,但这不是数组。

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 ' );sed表达式周围使用"而不是' (您的sed脚本包含' );
  2. Use # instead of / to limit each part of sed replace expression (your new token contains / );使用#而不是/来限制sed替换表达式的每个部分(您的新令牌包含/ );
  3. Use \ before each [ and ] in RE expression ( [ and ] are special RE characters);在 RE 表达式中的每个[]之前使用\[]是特殊的 RE 字符);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM