【问题标题】:How to remove white spaces (\t, \n, \r, space) form the beginning and the end of a string in shell?如何在 shell 中删除字符串开头和结尾的空格(\t、\n、\r、空格)?
【发布时间】:2015-12-09 11:20:29
【问题描述】:

如果存在字符串的开头和结尾,我想删除空格(\t、\n、\r、空格)

怎么做?

只有${str#*}这样的表达式才有可能吗?

【问题讨论】:

    标签: shell ash


    【解决方案1】:

    如果您使用的是 bash(您对 ${str#} 的想法似乎暗示了这一点),那么您可以使用它:

    echo "${str##[[:space:]]}" # trim all initial whitespace characters
    echo "${str%%[[:space:]]}" # trim all trailing whitespace characters
    

    【讨论】:

      【解决方案2】:

      你可以说

      sed -e 's/^[ \t\r\n]*//' -e 's/[ \t\r\n]*$//' <<< "string"
      #         ^^^^^^^^^^^           ^^^^^^^^^^
      #         beginning            end of string
      

      如果您的sed 版本支持,则使用\s 来匹配制表符和空格。

      【讨论】:

      • [[:space:]] 应该在任何符合 POSIX 的 sed 版本中工作。
      • @TomFenech 是的,应该,谢谢。我没有使用它,因为用户使用标签ash 进行标记,我记得他之前的问题是他使用旧系统,所以我不能依赖任何东西:)
      【解决方案3】:

      如果你可以使用sed 那么:

      echo "${str}" | sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//'
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-12-22
        • 1970-01-01
        • 2013-10-07
        • 1970-01-01
        • 1970-01-01
        • 2011-03-23
        • 2021-04-25
        • 2019-11-06
        相关资源
        最近更新 更多