Skip to content
Advertisement

replace in text with a var with some new lines

I have a var $MY_VAR which contains some new lines:

      hostAliases:
      - ip: "?.?.?.?"
        hostnames:
        - "m-0.mongodb-service.default.svc.cluster.local"
      - ip: "?.?.?.?"
        hostnames:
        - "m-1.mongodb-service.default.svc.cluster.local"
      - ip: "?.?.?.?"
        hostnames:
        - "m-2.mongodb-service.default.svc.cluster.local"
      - ip: "?.?.?.?"
        hostnames:
        - "m-3.mongodb-service.default.svc.cluster.local"

And a file my_file.txt with a value that has to be replaced:

some indented content ...
@@MY_VALUE@@
some indented content ...

I try to replace it using:

sed -i 's,@@MY_VALUE@@,'"$MY_VAR"',g' my_file.txt

That results into the following error:

sed: -e expression #1, char 36: unterminated `s' command

Advertisement

Answer

I finally found a totally different solution by removing the value to replace and split my file into two parts: my_file_part1.txt and my_file_part2.txt which are respectively the part before the variable and the part after the variable.

touch my_file.txt
cat my_file_part1.txt >> my_file.txt
echo "$MY_VAR" >> my_file.txt
cat my_file_part2.txt >> my_file.txt
Advertisement