【问题标题】:Return substring before dash followed by a digit in bash在破折号之前返回子字符串,后跟 bash 中的数字
【发布时间】:2018-07-26 22:31:31
【问题描述】:

我有一个字符串可以是以下之一:

1.) AA_BB-CC_xxxx-xx.y.y-xxxxxxxx-yyyyyy.tar.gz

或去掉前缀:

2.) CC_xxxx-xx.y.y-xxxxxxxx-yyyyyy.tar.gz

其中 A、B、C、D 是任意数量的字母,x 和 y 是数字。我需要从上面提取以下内容:

AA_BB-CC_xxxx
CC_xxxx

例子:

standalone_version-WIN_2012-16.3.2-20180627-131137.tar.gz
WIN_2008-16.3.2-20180614-094525.tar.gz

需要提取:

standalone_version-WIN_2012
WIN-2008

我试图从最后丢弃所有内容,直到遇到第一个破折号后跟一个数字。我正在使用以下内容,但它返回整个字符串:

name=${image_file%%-[0-9].*}

【问题讨论】:

    标签: string bash shell pattern-matching substring


    【解决方案1】:

    你快到了!而不是

    name=${image_file%%-[0-9].*}
    

    省略点:

    name=${image_file%%-[0-9]*}
    

    bash %% 字符串修剪中的表达式是patterns,而不是正则表达式。因此,* 单独匹配任意数量的字符,而不是正则表达式中的 .*

    示例(在 bash 4.4.12(3)-release 中测试):

    $ foo='standalone_version-WIN_2012-16.3.2-20180627-131137.tar.gz'
    $ bar='WIN_2008-16.3.2-20180614-094525.tar.gz'
    $ echo ${foo%%-[0-9].*}
    standalone_version-WIN_2012-16.3.2-20180627-131137.tar.gz
        # oops
    $ echo ${foo%%-[0-9]*}
    standalone_version-WIN_2012
        # no dot - works fine
    $ echo ${bar%%-[0-9]*}
    WIN_2008
        # same here.
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-11-08
      • 1970-01-01
      • 2015-06-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多