What is the reason that this sed replacement
echo "xaaa" | sed 's/a*//'
yields xaaa
. Isn't it trying to replace any consecutive a's by nothing?
Unless you add g
(for Global) after the last /
, sed
will only replace the first match.
Your a*
regex matches an empty string (*
means zero or more), so it replaces the empty string before x
with another empty string an then stops.
It is because *
means 0
or more matches so it matches an empty string and replaces with nothing.
However if you add g
(global) flag then it replaces all a
s:
echo "xaaa" | sed 's/a*//g'
x
No need to use the *
operator if you are using global substitution:
echo "xaaa" | sed 's/a//g'
x
The g
flag ensures that all occurrences of the pattern are replaced.