【问题标题】:AWK: replacing \' but not \\'AWK:替换 \' 但不是 \\'
【发布时间】:2017-09-18 08:18:17
【问题描述】:

我的字符串:

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

【问题讨论】:

    标签: regex awk gsub


    【解决方案1】:
    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恢复为\\'
    • 完成

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

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

    【讨论】:

    • 如果\'不在行首,可以简化为sed -E 's/([^\\])\\\x27/&\x27/g' ...或使用带有环视功能的工具... perl -pe 's/(?!<\\)\\\x27/$&\x27/g'
    • 我用过 gsub(/\\\\\x27/,"\x99\x0\x0\x99"); gsub(/\\\x27/,"\x27\x27"); gsub(/\x99\x0\x0\x99/,"\\\\\x27");因为 \x99 干扰了一些 unicode 字符。
    • 这也是's 的两倍。另外,不要使用十六进制 \x27 来表示 ',而是使用八进制 \047 - 请参阅 awk.freeshell.org/PrintASingleQuote
    • @EdMorton 感谢\x vs \0 的建议。关于'加倍,我认为OP希望将'加倍以使\'变为\''"so I have to replace single quotes to 2 single quotes."
    • @Pradeep wrt 你上面的评论,YMMV 将 nul 字符放在字符串中,因为一些 awk 实现可能假设 C 字符串不能包含 nul 字符,所以他们会做什么将取决于实现。
    【解决方案2】:

    替代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\''
    

    【讨论】:

    • 先生,这不能解决我的问题,原因有两个,第一,我想在 AWK 中使用它,第二,不应该更改 \\'。
    【解决方案3】:

    借用@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\\'
    

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

    【讨论】:

      猜你喜欢
      • 2020-06-24
      • 1970-01-01
      • 1970-01-01
      • 2019-04-21
      • 1970-01-01
      • 1970-01-01
      • 2016-10-29
      • 2015-04-01
      • 2014-01-04
      相关资源
      最近更新 更多