在破折号前返回子字符串,然后在bash中返回一个数字

时间:2018-07-26 22:31:31

标签: string bash shell pattern-matching substring

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

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].*}

1 个答案:

答案 0 :(得分:4)

您快到了!代替

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

省略点:

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

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

示例(在bash 4.4.12(3)-发行版中测试):

$ 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.
相关问题