-1

I am trying to replace name with a different name, which works but when I have "[]" it doesn't work.

#!/bin/bash
firstString="I love [Candy] Store"
firstChange="[Candy] Store"
secondString="Chocolate Store"
echo "${firstString//$firstChange/$secondString}"

I am expecting:

"I love Chocolate Store".

Working example:

#!/bin/bash
firstString="I love Candy Store"
firstChange="Candy Store"
secondString="Chocolate Store"
echo "${firstString//$firstChange/$secondString}"

Output:

I love Chocolate Store.

I am trying to make it work for both the cases.

Could someone please help me?

Thanks

1 Answers1

0

Well, this works:

#!/bin/bash
firstString="I love [Candy] Store"
firstChange="\[Candy\] Store"
secondString="Chocolate Store"
echo "${firstString//$firstChange/$secondString}"

It may not help you much; if your "change" string is input from somewhere you can't count on it being properly escaped.

The problem is that the bash expansion is treating the firstChange value as a pattern not a regular string.

Per this answer https://stackoverflow.com/a/2856010/200136 , printf "%q" is the solution:

#!/bin/bash
firstString="I love [Candy] Store"
firstChange="[Candy] Store"
printf -v quoteChange "%q\n" $firstChange
safeChange=$(echo $quoteChange)
secondString="Chocolate Store"
echo "${firstString//$safeChange/$secondString}"
Andrew McGuinness
  • 2,092
  • 13
  • 18