AWK:替换 \' 但不替换 \\'

AWK: replacing \' but not \\'

我的字符串:

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( /7/, "77" ); print; }'

备选sed方法:

s="So is there really more of you to love now? it\'s ...HB\'"
echo $s | sed "s/\([^\][\]\)'/''/g"

输出:

So is there really more of you to love now? it\''s ...HB\''
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 是不可见的 char
  • 首先将所有\'替换为\x99
  • 然后将所有 \' 替换为 \'
  • 最终将所有 \x99 恢复为 \'
  • 完成

如果出于某种原因需要 awk:

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

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

借用@Kent 的示例输入文件:

$ cat file
it\'s ...HB\'

你的问题不清楚,因为你没有提供预期的输出,而是将转义加倍:

$ awk '{gsub(/\\7/,"\n"); gsub(/\n|\7/,"\\7")} 1' file
it\'s ...HB\'

并加倍引号:

$ awk '{gsub(/\\7/,"\n"); gsub(/\7/,"&7"); gsub(/\n/,"\\7")} 1' file
it\''s ...HB\'

并将 \' 更改为 '':

$ awk '{gsub(/\\/,"\n"); gsub(/\7/,"77"); gsub(/\n/,"\\")} 1' file
it''s ...HB\'

无论您的输入文件中存在什么字符,这都会起作用,因为它使用换行符作为临时 \' 替换,并且换行符显然不能出现在该行中,因此您知道它是安全的用作临时值。