无法使用jq时,如何用Shell脚本批量替换JSON模板的指定值?
解决方案
针对无法使用jq的场景,提供两种可靠的批量替换方案,无需依赖额外工具:
方法一:sed精准替换占位符
利用sed的字符串替换命令(s),直接匹配模板中的固定占位符并替换为shell变量,避免整行替换破坏JSON格式。
步骤:
- 定义shell变量:
target_dir="/apps" # 对应dir_parm的value值 target_host="iass02" # 对应identifier的主机名 output_file="config_iass02.json" # 输出文件名 template_file="template.json" # 你的源JSON模板文件
- 执行sed替换并生成文件:
sed -e "s/\"changethis\"/\"${target_dir}\"/g" \ -e "s/\"hsotchangethis\"/\"${target_host}\"/g" \ "${template_file}" > "${output_file}"
注意:
如果target_dir包含/(比如路径/usr/local/apps),需要修改sed的分隔符避免冲突,比如改用#:
sed -e "s#\"changethis\"#\"${target_dir}\"#g" \ -e "s#\"hsotchangethis\"#\"${target_host}\"#g" \ "${template_file}" > "${output_file}"
方法二:Shell Here-Doc直接生成(更稳定)
如果模板格式固定,直接用here-doc将变量代入生成JSON文件,完全避免正则匹配的问题,适合批量场景。
批量处理示例:
- 创建一个配置列表文件
config_list.txt,每行格式为主机名 目录路径 输出文件名:
iass02 /apps config_iass02.json iass03 /data config_iass03.json iass04 /var/log config_iass04.json # ... 其他40+条记录
- 编写循环脚本批量生成:
while read -r host dir fname; do cat > "${fname}" <<EOF {"parameters": [ { "name": "dir_parm", "value": "${dir}" } ], "targets": [ { "identifier": "${host}" } ] } EOF done < config_list.txt
原sed命令失败原因
你之前的命令错误使用了整行替换(c命令),还不必要地转义了引号("),导致生成的JSON格式混乱,且未精准匹配占位符。改用上述两种方法即可解决问题。
内容的提问来源于stack exchange,提问作者user19742249
相关产品推荐
相关产品推荐

