2017-04-21 62 views
-1

我的字符串:AWK:替换“而不是\”

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; }' 

回答

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是单现状TE '
  • \x99是不可见的字符
  • 第一替换所有\\'通过\x99
  • 然后更换所有\'通过\\'
  • 终于恢复所有\x99\\'

如果AWK是需要一些reaseon:

kent$ cat f 
it\'s ...HB\\' 

kent$ awk '{gsub(/\\\\\x27/,"\x99");gsub(/\\\x27/,"&\x27");gsub(/\x99/,"\\\\\x27")}7' f 
it\''s ...HB\\' 
+0

我在类似的思路上想,谢谢:-) – Pradeep

+0

如果'\''不在行首,可以简化为'sed -E's /([^ \\])\\\ x27 /&\ x27/g'' ...或者使用带周期的工具...'perl -pe's /(?!<\\)\\\ x27/$&\ x27/g'' – Sundeep

+0

我使用了gsub(/ \\\\ X27 /, “\ X99 \ X0 \ X0 \ X99”); GSUB(/ \\\ X27 /, “\ X27 \ X27”); GSUB(/ \ X99 \ X0 \ X0 \ X99/“\\\\\ X27”);因为\ x99正在干扰某些unicode字符。 – Pradeep

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

先生,这并不能解决我的问题,原因有两个,一是我想要AWK,二是不应该改变。 – Pradeep

0

借款@肯特的样本输入文件:

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

,将工作,不管什么角色出现在你的输入文件,因为它使用换行符作为临时\\'更换和换行符显然不能存在于线上,所以你知道它的可以安全地用作临时值。