0

I'm trying to replace a bracketed text like [PROJECT_ID] with and env var PROJECT_ID...I tried this:

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

I get this: [$PROJECT_ID$PROJECT_ID$PROJECT_ID$PROJECT_ID$PROJECT_ID$PROJECT_ID$PROJECT_ID$PROJECT_ID$PROJECT_ID$PROJECT_ID]

I've tried lots of different ways but just can't seem to get this to work

Benjamin W.
  • 46,058
  • 19
  • 106
  • 116
lightweight
  • 3,227
  • 14
  • 79
  • 142
  • 2
    https://stackoverflow.com/questions/19151954/how-to-use-variables-in-a-command-in-sed is *almost* a duplicate (gist: use double quotes). Additionally, you have to escape `[` and `]` with `\[` and `\]`, or every single letter will be replaced instead of the complete string. Summary: `sed -i "s/\[PROJECT_ID\]/$PROJECT_ID/g" test.text`. – Benjamin W. Jan 31 '19 at 15:53
  • 1
    This question addresses the square bracket issue: https://stackoverflow.com/questions/10646418/how-to-replace-paired-square-brackets-with-other-syntax-with-sed – Benjamin W. Jan 31 '19 at 15:55

2 Answers2

0
  • Each run you append the same line to text.txt. So sed processes many lines
  • Single quotes like in 's|[PROJECT_ID]|$PROJECT_ID|g' use the text literally. But it seems, that you want to expand $PROJECT_ID.
  • In this case export is not needed.
  • It is not really clear, what you really want

Fixed code (my guess):

PROJECT_ID=adfaf@asdf.com
echo "[PROJECT_ID]" > test.text
sed -i -e "s|[PROJECT_ID]|$PROJECT_ID|g" test.text
Wiimm
  • 2,971
  • 1
  • 15
  • 25
0

You have to escape the brackets with a backslash to match them literally.

PROJECT_ID=adfaf@asdf.com
echo "[PROJECT_ID]" > test.text
sed -i -e "s|\[PROJECT_ID\]|$PROJECT_ID|g" test.text
Frank Neblung
  • 3,047
  • 17
  • 34