如何通过Bash脚本为多目录下的values.yaml添加指定对象
问题描述
我有分布在多个目录下的约200个values.yaml文件需要批量修正,已经实现了文件遍历逻辑,但不想使用yq工具,希望用Bash脚本完成以下操作:
- 检查文件是否包含
containers节点 - 若存在
containers,则在每个容器的imagename字段下方添加imageprefix: "" - 若容器段已经存在
imageprefix字段,则跳过该容器,避免重复添加
示例输入:
service: path: / ports: - port: 6055 containers: container1: name: service org: "company:" imagename: thirdparty-service tagprefix: "-" volumes: - name: pod-logs emptyDir: {} envMap: env: N_PERROUTE: 20 NUM_STREAM_THREADS_CONFIG: 10 NUM_STREAM_T
示例输出:
service: path: / ports: - port: 6055 containers: container1: name: service org: "company:" imagename: thirdparty-service imageprefix: "" tagprefix: "-" volumes: - name: pod-logs emptyDir: {} envMap: env: N_PERROUTE: 20 NUM_STREAM_THREADS_CONFIG: 10 NUM_STREAM_T
解决方案
可以用awk编写文本处理逻辑,配合Bash脚本实现批量操作。以下是完整的脚本:
#!/bin/bash # 处理单个values.yaml文件的函数 process_file() { local file="$1" # 使用awk处理文本,临时存储结果后替换原文件 awk ' BEGIN { in_containers = 0 in_container = 0 imagename_found = 0 indent = "" } # 进入containers块 /^containers:/ { in_containers = 1 print $0 next } # 离开containers块(当遇到非缩进的其他顶级节点时) in_containers && !/^[[:space:]]/ && !/^containers:/ { in_containers = 0 in_container = 0 imagename_found = 0 } # 在containers块内,匹配容器节点(比如container1:) in_containers && /^[[:space:]]+[^[:space:]]+:/ { in_container = 1 imagename_found = 0 print $0 next } # 在容器节点内,匹配imagename字段 in_container && /^[[:space:]]+imagename:/ { imagename_found = 1 indent = substr($0, 1, index($0, "imagename") - 1) print $0 next } # 当找到imagename后,检查下一行是否是imageprefix imagename_found == 1 { if ($0 !~ "^" indent "imageprefix:") { print indent "imageprefix: \"\"" } imagename_found = 0 } # 其他情况直接打印行 { print $0 } ' "$file" > "$file.tmp" && mv "$file.tmp" "$file" } # 遍历所有values.yaml文件(这里遍历当前目录及子目录下的所有目标文件) find . -name "values.yaml" -type f | while read -r file; do echo "Processing $file..." process_file "$file" done
脚本说明
- 状态机逻辑:通过
in_containers、in_container、imagename_found三个变量跟踪当前处理的位置,确保只在containers下的容器节点内操作。 - 缩进处理:捕获
imagename字段的缩进格式,保证插入的imageprefix和原字段缩进一致,维持YAML格式正确性。 - 去重检查:在插入前检查下一行是否已经存在
imageprefix,避免重复添加相同字段。 - 安全更新:先将处理结果写入临时文件,确认处理成功后再替换原文件,防止意外损坏原文件内容。
使用方法
- 将上述脚本保存为
update_values.sh - 赋予执行权限:
chmod +x update_values.sh - 运行脚本:
./update_values.sh
内容的提问来源于stack exchange,提问作者majan
相关产品推荐
相关产品推荐

