1

I am trying to replace a string inside a shell script by a string with special character:

name="test&commit"
echo "{{name}}" | sed "s/{{name}}/$name/g"

and the result I am getting is

test{{name}}commit

I know that adding \ before & will make it work but the name param is given by the user so I'd like my code to somoehow predict that. Do anybody knows how to achieve this ?

gniewleone
  • 445
  • 3
  • 7
  • 19

3 Answers3

2

You need to use another sed command to add a backslash before all the special characters in the given input string.

$ name="test&commit"
$ name1=$(sed 's/[^[:alpha:][:digit:][:blank:]]/\\&/g' <<<"$name")
$ echo $name1
test\&commit
$ echo "{{name}}" | sed "s/{{name}}/$name1/g"
test&commit

It would be minimized as,

$ name="test&commit"
$ echo "{{name}}" | sed "s/{{name}}/$(sed 's/[^[:alpha:][:digit:][:blank:]]/\\&/g' <<<"$name")/g"
test&commit
Avinash Raj
  • 172,303
  • 28
  • 230
  • 274
1

Slightly change way of providing the template and values:

$ cat template

   Dear {{name}}
    I hope to see you {{day}}.

(template is a file with {{var}}, to be instantiated with values)

$ name='Mary&Susan' day=tomorrow    perl -pe 's/{{(\w+)}}/$ENV{$1}/g' template

   Dear Mary&Susan,
    I hope to see you tomorrow.
JJoao
  • 4,891
  • 1
  • 18
  • 20
0

In perl you can turn off expressions with \Q \P.
I fill the vars template, placeholder and name:

$ echo "template=$template"
template=The name is {{name}} and we like that.
$ echo "placeholder=$placeholder"
placeholder={{name}}
$ echo "name=$name"
name=test&commit

The replacement will be performed with

$ echo $template | perl -pe 's/\Q'$placeholder'\E/'$name'/g'
The name is test&commit and we like that.
Walter A
  • 19,067
  • 2
  • 23
  • 43