0

I need to replace a string with contents of a json file. So my code goes like

value=$(<minified.json)
sed -i -e "s/<!--MyJson-->/$value/" file.html

I need to replace the contents of json file to <!--MyJson--> string in file.html.

Issue happens because some array elements in json have / so because of that it fails with error

sed: -e expression #1, char 438: unknown option to `s'

But I cant change that text in json. So how can i make my sed command to ignore the backslash in the copy text. Or how can i make it as a blind replace.

Please help

wanderors
  • 2,030
  • 5
  • 21
  • 35
  • Possible duplicate of [How to pass a variable containing slashes to sed](https://stackoverflow.com/questions/27787536/how-to-pass-a-variable-containing-slashes-to-sed) – Benjamin W. Sep 25 '18 at 21:52

1 Answers1

1

You can use different delimiters in substitution:

sed -i -e "s%<!--MyJson-->%$value%" file.html

(Provided % isn't used in the json).

Or switch to Perl where variables are first class citizens, not just expanding macros as in the shell:

value=$value perl -i~ -pe 's/<!--MyJson-->/$ENV{value}/' -- file.html
  • -p reads the input line by line and prints it after processing
  • the ENV hash contains environmental variables, setting the variable on the same line exports it to the following command
choroba
  • 231,213
  • 25
  • 204
  • 289