简体   繁体   English

如何将字符串与 bash 中的可选字符匹配?

[英]How can I match a string with optional characters in bash?

I have a small little script that deals with pipelines on Jenkins.我有一个处理 Jenkins 上的管道的小脚本。 It needs to be able to grab a file from a folder named after the pipeline name.它需要能够从以管道名称命名的文件夹中获取文件。

Most pipeline names follow this pattern: {Name}Pipeline/{Name}Pipeline.properties大多数管道名称都遵循这种模式: {Name}Pipeline/{Name}Pipeline.properties

However, a few pipelines have a three-digit version number appended, like so: {Name}Pipeline122/{Name}Pipeline122.properties但是,一些管道附加了三位数的版本号,如下所示: {Name}Pipeline122/{Name}Pipeline122.properties

In my script, I have a line that stores the path to this properties file in a variable: APP_PROPERTY_FILE=/path/to/file/${NAME}Pipeline/${NAME}Pipeline.properties在我的脚本中,我有一行将此属性文件的路径存储在一个变量中: APP_PROPERTY_FILE=/path/to/file/${NAME}Pipeline/${NAME}Pipeline.properties

Herein lies the problem?问题出在这里? How can I allow bash to match pipeline names without the version number AND pipeline names with the version number?如何允许 bash 匹配没有版本号的管道名称和带有版本号的管道名称?

Thanks!谢谢!

I believe that the user want to select a file that has optional element (3 digit number), and store the file name into shell variable.我相信用户想要 select 一个具有可选元素(3位数字)的文件,并将文件名存储到 shell 变量中。

Two challenges: (1) regular assignment var=/path/to/something* do not perform pathname expansion and (2) regular pattern matching do not support optional elements.两个挑战:(1)常规赋值 var=/path/to/something* 不执行路径名扩展和(2)常规模式匹配不支持可选元素。

Possible solutions are 'if-then-else' or using extended globs.可能的解决方案是“if-then-else”或使用扩展的 glob。 Both solutions assumed that one of the files exists.两种解决方案都假定其中一个文件存在。

APP_PROPERTY_FILE=/path/to/file/${NAME}Pipeline/${NAME}Pipeline.properties
if [ ! -f "$APP_PROPERY_FILE" ] ; then
APP_PROPERTY_FILE=$(echo /path/to/file/${NAME}Pipeline/${NAME}Pipeline[0-9][-0-9][0-9].properties)

Using extglob can also work.使用 extglob 也可以。

APP_PROPERTY_FILE=$(shopt -s extglob ; echo /path/to/file/${NAME}Pipeline/${NAME}Pipeline?([0-9][-0-9][0-9]).properties ; echo $1)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM