我的字符串:
INSERT INTO tb(str) VALUES('So is there really more of you to love now? it\'s ...HB\\');
现在,我必须使它与SQLite兼容,所以我必须将单引号替换为2个单引号。我尝试过这个AWK脚本,但我想只替换\'
而不是\\'
。
echo "So is there really more of you to love now? it\'s ...HB\\'" | awk '{ gsub( /\57\047/, "\047\047" ); print; }'
答案 0 :(得分:3)
kent$ cat f
it\'s ...HB\\'
kent$ sed 's/\\\\\x27/\x99/g;s/\\\x27/&\x27/g;s/\x99/\\\\\x27/g' f
it\''s ...HB\\'
\x27
是单引号'
\x99
是隐形字符\\'
替换为\x99
\'
替换为\\'
\x99
恢复为\\'
如果某些reaseon需要awk:
kent$ cat f
it\'s ...HB\\'
kent$ awk '{gsub(/\\\\\x27/,"\x99");gsub(/\\\x27/,"&\x27");gsub(/\x99/,"\\\\\x27")}7' f
it\''s ...HB\\'
答案 1 :(得分:0)
替代 sed 方法:
s="So is there really more of you to love now? it\'s ...HB\\'"
echo $s | sed "s/\([^\][\]\)'/\1''/g"
输出:
So is there really more of you to love now? it\''s ...HB\''
答案 2 :(得分:0)
借用@ Kent的样本输入文件:
$ cat file
it\'s ...HB\\'
你的问题不清楚,因为你没有提供预期的输出,但是将逃脱加倍:
$ awk '{gsub(/\\\\\047/,"\n"); gsub(/\n|\\\047/,"\\\\\047")} 1' file
it\\'s ...HB\\'
并加倍报价:
$ awk '{gsub(/\\\\\047/,"\n"); gsub(/\\\047/,"&\047"); gsub(/\n/,"\\\\\047")} 1' file
it\''s ...HB\\'
并将\'
更改为''
:
$ awk '{gsub(/\\\\/,"\n"); gsub(/\\\047/,"\047\047"); gsub(/\n/,"\\\\")} 1' file
it''s ...HB\\'
无论您的输入文件中包含哪些字符,它都会有效,因为它使用换行符作为临时\\'
替换,并且换行显然不能出现换行符,因此您知道它&#39 ;可以安全地用作临时值。