sed/gsed on MacOS Catalina not working as expected with star

Viewed 118

I tried the following:

# echo "12MB" | sed -e 's/[bm]\*//i'
12MB
# echo "12MB" | sed -e 's/[bm]\+//i'
12

I was expecting both to produce the same output (greedy match), but the one with the star does not. I tried also with gsed, but it was the same result. When I tried using -E # for extended re neither of the two forms works. An ubuntu docker container also behaves the same way.

Can someone help me understand why is that?

1 Answers

First, in sed "basic" regexp patterns * is for repetition, \* is a literal asterisk. So your example would be

# echo "12MB" | sed -e 's/[bm]*//i'
12MB

... which still doesn't produce your expected output.

The reason becomes apparent when you use a visible replacement:

# echo "12MB" | sed -e 's/[bm]*/!!!/i'
!!!12MB

The pattern matches right at the start of the string, for a repetition count of zero. After one match, replacement stops.

So you really want one or more repetitions, like in your working example.

Related