1

All the questions and answers i already read are not my solution. So, all i want to do is to replace the special char ' in bash.

This works:

A="abc"
B="${A//[b]/x}"

But this does not work:

A="a'b"
B="${A//[']/\'}"

Also, i have tried:

B="${A//[']/\\'}"
B="${A//[']/\\\'}"
B="${A//[']/\'''}"
B="${A//[']/'\\''}"

But B keeps to be a'b.

1 Answer 1

1

This way works:

A="a'b"
B="${A//\'/\\\'}"

Two notes:

  1. The [] are unnecessary when only one character is inside of them
  2. You need to escape \ and ' inside of the substitution.
1
  • The [] isn't unnecessary, but usually an alternative way of escaping special characters, as in "${A//[*]/x}" (could be perceived as more pleasing to the eyes than "${A//\*/x}"). However, in this case, the string quoting rules of bash interfere with the pattern parsing. In this case, replacing ['] with either \', [\'], or "'" would solve the issue. Likewise, the replacement string might be written "\'".
    – Kusalananda
    Commented Jun 3 at 9:13

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .