2017-04-21 75 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\\' 

,將工作,不管什麼角色出現在你的輸入文件,因爲它使用換行符作爲臨時\\'更換和換行符顯然不能存在於線上,所以你知道它的可以安全地用作臨時值。