0

I am trying to replate a pattern (that contains many specials chars) with a simple string that I have in a file called "file". I''m using sed to get it done. The command runs without any exception but the target file remains the same...

I'm trying to replace this:

<%=ENV["SECRET_KEY_BASE"]%>

with this (the content in the file):

88ce3e2c0fa0b667567dc370f8c62019ee88f1628ee1586651d7ea4a0faf18d0dbccaeb3f21c46109d2087ff31f07cf3734ce7a38f64f5a92cdf91dcb3494d1f** ... in a file called **secrets.yml

That's the commands I've tried but doesn't seem to work:

sed -i 's/<%=ENV["SECRET_KEY_BASE"]%>/$(cat file)/g' config/secrets.yml

also tried with variables this way, but nothing changed:

var1="<%=ENV["SECRET_KEY_BASE"]%>" && var2="`cat file`" && sed -i 's/$var1/$var2/g' config/secrets.yml

Does anyone have an idea what i'm missing here?

HatLess
  • 10,622
  • 5
  • 14
  • 32
adiac
  • 1
  • 1
  • I'm having trouble seeing exactly what your strings and command are; please use [an appropriate code format](https://meta.stackoverflow.com/questions/251361/how-do-i-format-my-code-blocks), so they're shown literally. But from what I can see, it looks like you have something in square-brackets in the pattern, and in a regular expression that has a [special meaning that probably isn't what you want](https://www.regular-expressions.info/posixbrackets.html). To match a literal bracket, see ["What's the regular expression that matches a square bracket?"](https://stackoverflow.com/questions/928072) – Gordon Davisson Apr 02 '22 at 02:39
  • Can `file` ever contain `&` or ```\``` or `/` characters? If so sed may not be your best choice, see [is-it-possible-to-escape-regex-metacharacters-reliably-with-sed](https://stackoverflow.com/questions/29613304/is-it-possible-to-escape-regex-metacharacters-reliably-with-sed). – Ed Morton Apr 02 '22 at 13:05

2 Answers2

0

There are two issues I see with what you have currently:

  1. 's/<%=ENV["SECRET_KEY_BASE"]%>/$(cat file)/g' is using single quotes which will prevent interpretation of the command to cat the file
  2. You need to escape a few things in the comparison string like: <%=ENV\[\"SECRET_KEY_BASE\"\]%>

Putting those things together, this is working for me:

sed -i "s/<%=ENV\[\"SECRET_KEY_BASE\"\]%>/$(cat file)/g" secrets.yml
alex9552
  • 231
  • 1
  • 5
0

Certain special characters must be escaped when using sed. In this case it's the square brackets and the double quotes in the string to be replaced.

sed -i "s|<%=ENV\[\"SECRET_KEY_BASE\"\]%>|88ce3e2c0fa0b667567dc370f8c62019ee88f1628ee1586651d7ea4a0faf18d0dbccaeb3f21c46109d2087ff31f07cf3734ce7a38f64f5a92cdf91dcb3494d1f|g" secrets.yml
c0rnpuk3
  • 39
  • 7