【问题标题】:How would I replace a single quote (') with a backslash then single quote (\') using sed?如何用反斜杠替换单引号 ('),然后使用 sed 替换单引号 (\')?
【发布时间】:2011-12-25 15:05:49
【问题描述】:

如何将单引号 (') 替换为反斜杠,然后使用 sed 替换单引号 (\')?

sed s/\'/\\\'/

不会工作,因为你永远不会写文字。

sed ":a;N;s/\'/\\'/g" <file1 >file2

不起作用,因为反斜杠将不再转义引号,它被视为正则表达式引号。

【问题讨论】:

  • 适用于 Mac OS - 您的里程可能会有所不同...

标签: sed terminal


【解决方案1】:

怎么样: sed "s,',BBBB',g" 文件 其中 B 是一个反斜杠 ... 即 4 个反斜杠 ...

【讨论】:

    【解决方案2】:

    使用 -e 选项。

    sed -e s/\'/\\'/g file2

    【讨论】:

      【解决方案3】:

      尝试以下方法:

      sed -e s/\'/\\\\\'/g input > output
      

      为了证明这是有效的:

      echo "Hello 'World'" | sed -e s/\'/\\\\\'/g
      

      输出应该是:

      Hello \'World\'
      

      【讨论】:

        【解决方案4】:

        只需引用替换

        $ echo \' | sed s/\'/"\\\'"/
        $ \'
        

        例如

        $ cat text1
        this is a string, it has quotes, that's its quality
        $ sed s/\'/"\\\'"/ text1 > text2
        $ cat text2
        this is a string, it has quotes, that\'s its quality
        

        【讨论】:

        • +1 :) 与之相反的正是我所需要的。 sed s/"\\\'"/\'/g
        【解决方案5】:

        这似乎有效:

        <<<"''''" sed 's/'\''/\\&/;s/\('"'"'\)\(..\)$/\\\1\2/;'s/\'\'$/\\\\\'\'/";s/'$/\\\'/"
        \'\'\'\'
        

        这显示了 4 种不同的方式,其中可以使用 sed 将单引号替换为反斜杠后跟单引号。

        1. &lt;&lt;&lt;\' sed 's/'\''/\\&amp;/'
        2. &lt;&lt;&lt;\' sed 's/\('"'"'\)/\\\1/'
        3. &lt;&lt;&lt;\' sed s/\'/\\\\\'/
        4. &lt;&lt;&lt;\' sed "s/'/\\\'/"

        将它们完全替换为上述正则表达式的四个单引号即可达到预期的效果。

        【讨论】:

          猜你喜欢
          • 2022-01-27
          • 2015-08-29
          • 1970-01-01
          • 1970-01-01
          • 2014-09-25
          • 2019-11-29
          • 2018-02-13
          • 2017-09-14
          • 1970-01-01
          相关资源
          最近更新 更多