【问题标题】:how to replace "/" in a POSIX sh string如何替换 POSIX sh 字符串中的“/”
【发布时间】:2014-02-20 15:51:09
【问题描述】:

要替换 bash 字符串 str 中的子字符串,我使用:

str=${str/$pattern/$new}

但是,我目前正在编写一个脚本,该脚本将使用ash 执行。

我有一个包含'/' 的字符串,我想使用上述语法来替换我的字符串中的'/',但它不起作用。

我试过了:

str=${str///a}
str=${str/\//a}
str=${str/'/'/a}

但它们不起作用

我该如何解决这个问题?

【问题讨论】:

    标签: linux string shell ash


    【解决方案1】:

    此参数扩展是对 POSIX sh 的 bash 扩展。如果您查看 the relevant section of IEEE standard 1003.1,您会发现它不是必需的功能,因此仅承诺 POSIX 合规性的外壳,例如 ash,没有义务实施它,也没有义务遵守他们无论如何都应该这样做的任何特定的正确性标准..

    如果您想要 bash 扩展,则需要使用 bash(或其他类似扩展的 ksh 衍生产品)。

    在此期间,您可以使用其他工具。例如:

    str=$(printf '%s' "$str" | tr '/' 'a')
    

    str=$(printf '%s' "$str" | sed -e 's@/@a@g')
    

    【讨论】:

    • @Anis_Stack POSIX shell 语言根本不需要它工作。查看pubs.opengroup.org/onlinepubs/009695399/utilities/… 中的扩展列表——您会发现${foo//bar/baz} 不在列表中。
    • @Anis_Stack ...并且由于ash 只承诺与POSIX sh 兼容,而POSIX sh 不需要该功能,因此任何半生不熟的实现甚至都不是错误,这只是未指定的行为。
    猜你喜欢
    • 2020-07-22
    • 2018-04-30
    • 2014-01-22
    • 2018-10-19
    • 2011-02-19
    • 1970-01-01
    • 2011-03-01
    相关资源
    最近更新 更多