【问题标题】:Replace Double quotes with space用空格替换双引号
【发布时间】:2018-08-06 18:56:56
【问题描述】:

这可能是这里讨论最多的话题之一。我尝试了几乎所有在这里找到的命令和其他调整,但有些东西似乎做得不好。

我想用空格/空白替换文件中的所有双引号

我在尝试执行此命令时看到以下错误。

sed "s/"/ \''/g' x_orbit.txt > new.tx
sed: -e expression #1, char 3: unterminated `s' command

【问题讨论】:

  • 谁能告诉我如何在 sed 中定义空间?
  • 空格就是空格。真正的问题是使用双引号而不是单引号。查看here了解更多详情。

标签: shell unix awk sed grep


【解决方案1】:

你已经接近了。只需使用单引号,因此 shell 不会尝试扩展 sed 命令中的元字符:

sed 's/"/ /g' x_orbit.txt > new.txt

【讨论】:

  • 或sed 'y/"/ /' x_orbit.txt > new.txt
【解决方案2】:

你可以试试tr 例如:

tr '"' ' ' < x_orbit.txt > new.txt

【讨论】:

    【解决方案3】:

    您提供的脚本:

    sed "s/"/ \''/g' x_orbit.txt > new.tx
    

    意思是:

    sed    # invoke sed to execute the following script:
    "      # enclose the script in double quotes rather than single so the shell can
           # interpret it (e.g. to expand variables like $HOME) before sed gets to
           # interpret the result of that expansion
    s/     # replace what follows until the next /
    "      # exit the double quotes so the shell can now not only expand variables
           # but can now do globbing and file name expansion on wildcards like foo*
    /      # end the definition of the regexp you want to replace so it is null since
           # after the shell expansion there was no text for sed to read between
           # this / and the previous one (the 2 regexp delimiters)
    \'     # provide a blank then an escaped single quote for the shell to interpret for some reason
    '/g'    # enclose the /g in single quotes as all scripts should be quoted by default.
    

    这与正确的语法相差甚远,这有点令人震惊,这就是为什么我在上面剖析它以帮助您理解您所写的内容,以便您了解它为什么不起作用。你从哪里得到这样写它的想法(或者换一种方式 - 你认为该脚本中的每个字符是什么意思?我在问,因为它表明了对引用和转义如何在 shell 中工作的基本误解,所以它如果我们能帮助纠正这种误解而不仅仅是纠正那个脚本,那就太好了。

    当您在 shell 中使用任何脚本或字符串时,只需始终将其括在单引号中:

    sed 'script' file
    var='string'
    

    除非你需要使用双引号来让变量扩展,然后使用双引号,除非你需要不使用引号来让通配符和文件名扩展发生。

    【讨论】:

      【解决方案4】:

      awk 版本:

      awk '{gsub(/"/," ")}1' file
      

      gsub 用于替换
      1 始终为真,因此打印行

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-08-08
        • 1970-01-01
        • 2014-12-11
        • 2011-01-22
        • 2014-02-19
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多