使用sed将括号替换为env var

时间:2019-01-31 15:41:53

标签: bash sed

我正尝试将[PROJECT_ID]之类的方括号文本替换为and env var PROJECT_ID ...我尝试过:

export PROJECT_ID=adfaf@asdf.com
echo "[PROJECT_ID]" >> test.text
sed -i -e 's|[PROJECT_ID]|$PROJECT_ID|g' test.text

我明白了: [$PROJECT_ID$PROJECT_ID$PROJECT_ID$PROJECT_ID$PROJECT_ID$PROJECT_ID$PROJECT_ID$PROJECT_ID$PROJECT_ID$PROJECT_ID]

我尝试了许多不同的方法,但似乎无法使其工作

2 个答案:

答案 0 :(得分:0)

  • 每次运行您附加在同一行向的text.txt。 sed处理了很多行
  • 单引号等在's|[PROJECT_ID]|$PROJECT_ID|g'使用文本字面。但似乎您想扩展$ PROJECT_ID。
  • 在这种情况下,不需要export
  • 这是不是真的清楚了,你真正想要

固定代码(我的猜测):

PROJECT_ID=adfaf@asdf.com
echo "[PROJECT_ID]" > test.text
sed -i -e "s|[PROJECT_ID]|$PROJECT_ID|g" test.text

答案 1 :(得分:0)

您必须使用反斜杠将括号转义以使其在字面上匹配。

PROJECT_ID=adfaf@asdf.com
echo "[PROJECT_ID]" > test.text
sed -i -e "s|\[PROJECT_ID\]|$PROJECT_ID|g" test.text