【问题标题】:How to replace a string containing "\u2015"?如何替换包含“\u2015”的字符串?
【发布时间】:2016-10-30 10:37:10
【问题描述】:

有谁知道如何在 SED 命令中替换包含 \u2015 的字符串,如下例所示?

sed -ie "s/some text \u2015 some more text/new text/" inputFileName

【问题讨论】:

  • 取决于\u2015 代表什么。

标签: linux sed sh


【解决方案1】:

不确定这是否正是您所需要的,但也许您应该看看 native2ascii 工具来转换此类 unicode 转义。

通常它会将所有无法在 ISO-8859-1 中显示的字符替换为其 unicode(用 \u 转义),但它也支持反向转换。假设你有一些 UTF-8 文件,名为“input”,包含\u00abSome \u2015 string\u00bb,然后执行

native2ascii -encoding UTF-8 -reverse input output

将产生带有«Some ― string» 的“输出”文件。

【讨论】:

    【解决方案2】:

    您只需要避开存在的斜线。下面的示例在GNU sed version 4.2.1 中运行良好

    $ echo "some text \u2015 some more text" | sed -e "s/some text \\\u2015 some more text/abc/"
    $ abc
    

    您也不必使用-i 标志,根据man 页面仅用于就地编辑files

    -i[SUFFIX], --in-place[=SUFFIX]
    
        edit  files  in place (makes backup if extension supplied).  The default operation mode is to break symbolic and hard links.  This can be changed with --follow-symlinks and
              --copy.
    

    【讨论】:

    • 永远不要在脚本周围使用双引号,始终使用单引号。在这种情况下,如果你这样做,你会发现你不需要这么多的转义。
    猜你喜欢
    • 1970-01-01
    • 2018-12-13
    • 2017-11-19
    • 2021-06-08
    • 2011-03-10
    • 1970-01-01
    • 2020-04-05
    • 2019-05-25
    • 1970-01-01
    相关资源
    最近更新 更多