Bash 删除后缀(如果存在)



我将有一个变量(我们称之为$name(,它可以遵循以下模式之一;

foo
foo-green
foo-blue
foo-bar
foo-bar-green
foo-bar-blue

Bash 中最轻松的方法是什么来去除-green-blue后缀(如果存在(,而其余部分保持不变?

参数替换

name="${name%-green}"
name="${name%-blue}"

使用extglob,您只需一步即可完成此操作:

# utility function to strip green or blue from end of string
cstrip() { shopt -s extglob; echo "${1%-@(green|blue)}"; }
# use it as
cstrip 'foo-bar-blue'
foo-bar
cstrip 'foo-bar-green'
foo-bar
cstrip 'foo-blue'
foo
cstrip 'foo-bar'
foo-bar

带 bash:

[[ $name =~ (.*)(-green|-blue) ]] && name="${BASH_REMATCH[1]}"
echo "$name"

相关内容

最新更新