【问题标题】:Cutting a section out of a string and returning the opposite从绳子上剪下一段并返回相反的部分
【发布时间】:2016-02-23 00:43:48
【问题描述】:

给定一个目录树,假设我不知道该字符串在哪里结束,我将如何从字符串中删除分隔符的最后一个字段并返回没有该分隔符的字符串?

例如,给定

/1/2/3/4/5

我知道我可以返回 5

cut -f 5 -d '/'

如果我知道最后一个字段是第 5 个字段,或者如果 a=/1/2/3/4/5

echo ${a##*/}

选择最后一个字段。但是我将如何返回原始字符串减去最后一个字段?即

/1/2/3/4

【问题讨论】:

    标签: regex bash glob


    【解决方案1】:

    您可以使用%%% 运算符代替##。来自 Bash 手册页:

     ${parameter%word}
     ${parameter%%word}
              The word is expanded to produce a pattern just as  in  pathname  expan-
              sion.   If the pattern matches a trailing portion of the expanded value
              of parameter, then the result of the expansion is the expanded value of
              parameter  with  the  shortest matching pattern (the ``%'' case) or the
              longest matching pattern (the ``%%'' case) deleted.  If parameter is  @
              or  *,  the  pattern  removal  operation  is applied to each positional
              parameter in turn, and the expansion is the resultant list.  If parame-
              ter  is  an array variable subscripted with @ or *, the pattern removal
              operation is applied to each member of  the  array  in  turn,  and  the
              expansion is the resultant list.
    

    简而言之,${a%/*} 可以解决问题。

    【讨论】:

      【解决方案2】:

      你可以给剪切一个范围的字段

      cut -f 1-4 -d '/'
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-11-06
        • 1970-01-01
        • 2018-11-04
        • 2016-06-10
        • 2012-12-26
        • 1970-01-01
        相关资源
        最近更新 更多