我有一个字符串,可以是以下之一:
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].*}
最佳答案
你就快到了!而不是
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.
关于string - 在 bash 中返回破折号之前的子字符串,后跟数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51548357/