【问题标题】:Bash script replacing single quote with single quote and backslashBash 脚本用单引号和反斜杠替换单引号
【发布时间】:2014-09-25 23:31:53
【问题描述】:

我有一个长字符串,其中包含单引号 (')。我需要将此发送到 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 的示例,但无法弄清楚这一点。 感谢任何帮助。

谢谢

【问题讨论】:

  • 你看到this的回答了吗?你能适应吗?
  • 很遗憾没有,因为我需要用两个字符(反斜杠和单引号)替换一个字符(单引号)
  • 我认为这样的想法一定是解决方案bar=${foo//\'/\\\\'}

标签: mysql bash quotes


【解决方案1】:

你可以使用sed "s/'/\\\'/g":

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

【讨论】:

    【解决方案2】:

    使用纯 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 \'
    

    【讨论】:

    • @AvinashRaj:这适用于 BASH。 You can see this working demo
    • 你的 BASH 版本是多少?试试这个命令:bash -c "s=\"This is the first single quote ', and this is the second '\"; echo \"${s//\'/\'}\" "
    猜你喜欢
    • 2017-09-14
    • 2022-01-27
    • 1970-01-01
    • 1970-01-01
    • 2011-12-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-09
    相关资源
    最近更新 更多