Bash脚本用单引号和反斜杠替换单引号

时间:2014-08-03 07:40:57

标签: mysql bash quotes

我有一个长字符串,其中包含单引号(')。我需要将它发送到mysql所以我试图替换"'"用" \'"在INSERT语句中的变量中。

示例:

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

应该成为

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

我已经看过几个脚本替换和sed的例子,但是无法想出这个。 感谢任何帮助。

由于

2 个答案:

答案 0 :(得分:1)

您可以使用sed "s/'/\\\'/g"

echo "This is the first single quote ', and this is the second '" | sed "s/'/\\\'/g"

答案 1 :(得分:1)

使用纯BASH字符串操作:

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 \'