如何用Bash修改YAML文件中指定服务的image值?
仅更新YAML中tracking-service下的image字段值
问题描述
需要修改给定YAML文件中tracking-service节点下的image字段值,原尝试的sed命令未达到预期效果。
原始YAML文件
global: environment: - license_key: uasd89ys8dashlkas services: tracking-service: image: mmg.idom.tracking-1.3.0.jar #<= 需要仅修改这个值 route_path: "/tracking/**" environment: - LOGGING_FILE: /dev/gtm/logs/tracking-service/tracking-service.log mem_limit: 384m restart: always health_endpoint: /tracking/health location-mobile-health: image: mmg.ips.location-1.4.6.jar route_path: "/location-mobile/**" environment: - LOGGING_FILE: /dev/gtm/logs/location-mobile-health/location-mobile-health.log mem_limit: 128m restart: always
已尝试的无效命令
sed -i -e "/^tracking-service:/,/image:/{/^\([[:space:]]*image: \).*/s//\$NewValue/}" \test.yaml
预期输出
global: environment: - license_key: uasd89ys8dashlkas services: tracking-service: image: NEW-value.jar #<= 修改后的目标值 route_path: "/tracking/**" environment: - LOGGING_FILE: /dev/gtm/logs/tracking-service/tracking-service.log mem_limit: 384m restart: always health_endpoint: /tracking/health location-mobile-health: image: mmg.ips.location-1.4.6.jar route_path: "/location-mobile/**" environment: - LOGGING_FILE: /dev/gtm/logs/location-mobile-health/location-mobile-health.log mem_limit: 128m restart: always
解决方案
方法1:修复后的sed命令
原sed命令的范围匹配逻辑错误,且变量引用、替换格式存在问题。使用以下命令可精准匹配tracking-service节点下的image行:
NEW_VALUE="NEW-value.jar" sed -i -e '/^[[:space:]]*tracking-service:/,/^[[:space:]]*[^[:space:]]/{s/^[[:space:]]*image: .*/\t\timage: '"$NEW_VALUE"'/}' test.yaml
命令说明:
/^[[:space:]]*tracking-service:/,/^[[:space:]]*[^[:space:]]/:匹配从tracking-service行开始,到下一个同级节点(非空且非纯缩进开头的行)结束的范围s/^[[:space:]]*image: .*/\t\timage: '"$NEW_VALUE"'/:在上述范围内,替换所有image:开头的行,保持与原文件一致的缩进(此处用两个制表符,可根据实际格式调整)
方法2:使用专门的YAML工具(推荐)
sed适合处理纯文本,但YAML是结构化数据,使用yq(YAML专用处理工具)能更安全可靠地修改字段,避免缩进、格式变化导致的错误:
安装yq(以Linux为例):
# Debian/Ubuntu sudo apt install yq # RHEL/CentOS sudo yum install yq # 二进制下载方式 wget https://github.com/mikefarah/yq/releases/latest/download/yq_linux_amd64 -O /usr/bin/yq && chmod +x /usr/bin/yq
修改命令:
yq eval '.services."tracking-service".image = "NEW-value.jar"' -i test.yaml
该命令直接定位到services.tracking-service.image节点修改值,无需考虑文本匹配或缩进问题,是处理YAML的最优方案。
内容的提问来源于stack exchange,提问作者endlessCode
相关产品推荐
相关产品推荐

