limmer
November 15, 2009, 1:19pm
1
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% * *}
limmer
November 15, 2009, 3:17pm
3
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)}
X-Or
November 22, 2009, 9:23am
6
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.
danmero
November 22, 2009, 10:03am
8
# 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
X-Or
November 22, 2009, 10:44am
9
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
X-Or
November 23, 2009, 10:02am
11
It do, thanks.
The % char is used to read from the end of str ?