Bash string replace

Bash shell. I'm trying to filter a string taken from user input. I can replace one word at a time. This method supports regex, so is it possible to replace various words at a time?

STRING="Hello World! word1 word2";

FILTERED=${STRING/word1|word2/}; # Not working: replace 2 or more words ???

echo $FILTERED;

Parameter expansion uses shell pattern matching, not regex.
You could use e.g. to filter out either or both words and the space before it.

FILTERED=${STRING//@( word1| word2)/}

You need to use a double slash otherwise it will just match one word in case there are two matching words.

or, if you do not seek to filter out these specific words, just plain:

FILTERED=${STRING% * *}

I tried this code but is not functional (at least in bash). FILTERED still outputs the string unchanged. The second code posted does work though.

FILTERED=${STRING//@( word1| word2)/}

Does this work?

bash code:

shopt -s extglob
STRING="Hello World! word1 word2"
FILTERED=${STRING//@( word1| word2)/}
echo $FILTERED

---------- Post updated at 12:55 PM ---------- Previous update was at 12:28 PM ----------

This should work too:

FILTERED=${STRING/+( word1| word2)}

Yes, shopt was missing. :b:

Bonjour,

Comment se nomme ce type de filtre ? es-ce les expressions r�guli�res ?

It is called extended shell pattern matching, also called extended globbing. These are not regular expressions.

# STRING="Hello World! word1 word2 AND another word3 at the END.";
# FILTERED=${STRING// word[1-9]/};
# echo "$FILTERED"
Hello World! AND another at the END.

Works on bash

Ok thanks.

str="It's cold, very cold"
pattern=${str/cold/hot}
echo $pattern

Is possible to replace the second "cold" by "hot" and keep the first "cold" with extended globbing ?

echo ${str%cold}hot

But I suspect that does not satisfy your question :wink:

It do, thanks.
The % char is used to read from the end of str ?