Philippe Pij
Philippe Pij

Reputation: 23

Variable name expansion multiple substitution

I'm wondering how to substitute multiple patterns with variable expansion.

VAR=A_B_C_D_E

Result I want is A_C_E without using temp variable.

RESULT_TMP=${VAR/_B/}
RESULT=${RESULT_TMP/_D/}

I did some trial like this:

${${VAR/_B/}/_D/}

without any success.

Any idea?

Upvotes: 2

Views: 74

Answers (1)

anubhava
anubhava

Reputation: 785266

You can use this glob pattern in BASH string substitution:

s='A_B_C_D_E'
echo "${s//_[BD]/}"
A_C_E

_[BD] will match _B or _D and // will do global replacement.


EDIT: On additional question of:

but in case where B and D are strings: A_FOO_C_BAR_E

You can use extglob in that case:

shopt -s extglob

s=`A_FOO_C_BAR_E`
echo "${s//_@(FOO|BAR)/}"
A_C_E

Upvotes: 5

Related Questions