0

I have the basic html, for example:

<html>
<head>
<title>My App</title>
</head>
<body>
<div id="app"></div>
<script>window.API_URL = ''</script>
</body>
</html>

I need to replace '' by environment variable. Env variable will contain slashes (for example: https://website.com/api

I'm trying to use the following code but it just outputted $MY_API_URL instead of real value and </script> text got removed:

cat index.html | sed -i -e '/window\.API_URL =/ s/= .*/= \"${MY_API_URL}\";/' index.html 

Given MY_API_URL=https://somesite.com, I expect to get <script>window.API_URL = "https://somesite.com";</script>.

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
D.Mark
  • 537
  • 1
  • 11
  • 23
  • 1
    Actually, [sed substitution with Bash variables](https://stackoverflow.com/questions/7680504/sed-substitution-with-bash-variables) cannot be used as duplicate reason because it does not solve the current problem, namely, get ``, as the `` part will be removed. OP needs to keep this part inside the result. I edited the question to reflect this. – Wiktor Stribiżew Feb 28 '21 at 20:38

1 Answers1

3

You can use

sed -i 's/\(window\.API_URL =\)[^<]*/\1 "'"${MY_API_URL//\//\\\/}"'";/' index.html

See the online demo.

Details:

  • \(window\.API_URL =\)[^<]* - a POSIX BRE pattern that matches and captures into Group 1 window.API_URL = text and then matches any zero or more chars other than <
  • \1 "'"${MY_API_URL//\//\\\/}"'"; - a replacement that puts back the value captured into Group 1 (\1) and then adds a space, ", the MY_API_URL value and then "; string.

The ${MY_API_URL//\//\\\/} is an example of variable expansion where a / is replaced with \/ (thanks to // after the variable name, all occurrences are replaced).

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563