0

I have a long string which contains single quotes (') in it. I need to send this to mysql so I am trying to replace "'" with "\'" in the variable during the INSERT statement.

Example:

"This is the first single quote ', and this is the second '"

should become

"This is the first single quote \', and this is the second \'"

I've seen several examples with script replace and sed, but cannot figure this one out. Appreciate any help.

Thanks

anubhava
  • 761,203
  • 64
  • 569
  • 643
  • have you seen [this](http://stackoverflow.com/questions/5928156/replace-a-space-with-a-period-in-bash) answer? can you adapt it? – Jens Aug 03 '14 at 07:44
  • unfortunately not, since i need to replace one character (single quote), with two characters (backslash and single quote) – user3903491 Aug 03 '14 at 07:50
  • i think somethink like that must be the solution `bar=${foo//\'/\\\\'}` – Jens Aug 03 '14 at 07:53

2 Answers2

1

You can use sed "s/'/\\\'/g":

echo "This is the first single quote ', and this is the second '" | sed "s/'/\\\'/g"
Gergo Erdosi
  • 40,904
  • 21
  • 118
  • 94
1

Using pure BASH string manipulation:

s="This is the first single quote ', and this is the second '"
s="${s//\'/\'}"
echo "$s"
This is the first single quote \', and this is the second \'
anubhava
  • 761,203
  • 64
  • 569
  • 643
  • @AvinashRaj: This works in BASH. [You can see this working demo](http://ideone.com/KPYnxf) – anubhava Aug 03 '14 at 08:39
  • What is your BASH version? Try this command: `bash -c "s=\"This is the first single quote ', and this is the second '\"; echo \"${s//\'/\'}\" "` – anubhava Aug 03 '14 at 09:35