If switching to zsh
is an option, you can use ${VAR:#value}
or the ksh93 style ${VAR/#%value}
.
${var/pattern[/replacement]}
comes from ksh93 and has also been copied by bash. ksh93 also lets you anchor the search at the start with ${var/#pattern}
or end with ${var/%pattern}
but doesn't let you combine both. bash doesn't either but zsh does with ${var/#%pattern}
.
See info zsh 'Parameter Expansion'
for details.
With the extendedglob
option on, you also get (#s)
and (#e)
glob pattern operators (Globbing Flags) that match respectively at the s
tart (like regex ^
) and e
nd (like regex $
) of the subject, so after set -o extendedlob
, you can also use ${VAR/(#s)value(#e)}
or ${VAR#value(#e)}
or ${VAR%(#s)value}
.
If it's about prompt expansion, you'd be better of preparing the text you want to include in a precmd
hook (or $PROMPT_COMMAND
in bash), something like:
prompt-from-VAR() {
case $VAR in
(value) psvar[1]=;;
(something-else) psvar[1]=OTHER;;
(*) psvar[1]=$VAR;;
esac
}
autoload add-zsh-hook
add-zsh-hook precmd prompt-from-VAR
PS1='%1v$ '
(here using $psvar
and %v
instead of the more dangerous prompsubst
option).
In bash that has no equivalent to psvar
or precmd
hooks:
PROMPT_COMMAND="$PROMPT_COMMAND"'
case $var in
(value) promt_VAR=;;
(something-else) prompt_VAR=OTHER;;
(*) prompt_VAR=$VAR;;
esac'
PS1='${prompt_VAR}$ '