【问题标题】:Replace placeholder in file with multiple lines in shell script用shell脚本中的多行替换文件中的占位符
【发布时间】:2019-12-20 20:25:47
【问题描述】:

对于 CI / CD 管道,我想将 nginx.conf 文件中的占位符替换为生成的映射,如下所示:

map $cookie_language $lang {
  default en
  en en
  de de
  es es
}

在 nginx.conf 文件中有占位符 # REPLACE_ME_WITH_LANGUAGE_MAP,我将其替换为以下命令:

sed -i -e "s/# REPLACE_ME_WITH_LANGUAGE_MAP/$languagemap/g" ./ci/nginx.conf

完整的脚本如下所示:

languagemap='map $cookie_language $lang {'
firstlanguage=$(jq -r '.locales[0]' src/assets/locales.json | jq -r '.build')
languagemap="${languagemap}|  default   $firstlanguage"
for locale in $(jq -r '.locales[] | @base64' src/assets/locales.json); do
  lang=$(echo "$locale" | base64 --decode | jq -r '.build')
  languagemap="${languagemap}|  $lang   $lang"
  npm run ci-build -- --output-path ${OUTPUT_PATH}/$lang --configuration=${ANGULAR_CONFIGURATION} --i18n-format=xlf --i18n-file=src/locale/messages.$lang.xlf --i18n-locale=$lang
done
languagemap="${languagemap}|}"
sed -i "t" "s/# REPLACE_ME_WITH_LANGUAGE_MAP/$languagemap/g" ./ci/nginx.conf

运行这个总是会弹出:

+ sed -i tmp s/# REPLACE_ME_WITH_LANGUAGE_MAP/map $cookie_language $lang {|  default   en|  en   en|  de   de|}/g ./ci/nginx.conf
sed: can't find label for jump to `mp'

有什么意义?

【问题讨论】:

标签: bash shell sed


【解决方案1】:

完整脚本的第 10 行是

sed -i "t" <replace-command-script> <input-file>

sed 正确地将"t" 解释为“分支到”命令,这会引发错误。

将此行替换为您上面提供的变体,即

sed -i -e '<replace command script>' <input-file>

这应该可以解决问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-29
    • 2017-11-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多