3

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?

jinawee
  • 473
  • 5
  • 15
  • See: [The Stack Overflow Regular Expressions FAQ](http://stackoverflow.com/a/22944075/3776858) – Cyrus Aug 20 '18 at 16:54

3 Answers3

5

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.

SLaks
  • 800,742
  • 167
  • 1,811
  • 1,896
3

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 as:

echo "xaaa" | sed 's/a*//g'
x
anubhava
  • 664,788
  • 59
  • 469
  • 547
  • 1
    It reduces the number of replacement in the string `xaaa` by one, but it *increases* the number of replacements in `Some line with the string xaaa` by ~25 – that other guy Aug 20 '18 at 16:59
1

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.

Paolo
  • 10,935
  • 6
  • 23
  • 45