Is sed \{x,y\} range greedy

regular expressionsed

I would like to know if, for instance, \{x,y\} in sed will try to match as much or as little as possible characters.

Also, can someone explain to me the bellow unexpected behaviour of sed?

echo "baaab" | sed 's/a\{1,2\}//'
bab

echo "baaab" | sed 's/a\{0,2\}//'
baaab

In the first line, sed becomes greedy, in the second apparently it doesn't, is there a reason for that?

I'm using GNU sed version 4.2.1.

Best Answer

a\{0,2\} will match the empty string at the start of the line (actually, any empty string, but g wasn't specified):

$ echo "baaab" | sed 's/a\{0,2\}/y/' 
ybaaab

Since GNU sed does matching from left to right, and a global replacement wasn't specified, only the start of the line matched. If you'd used g:

$ echo "baaab" | sed 's/a\{0,2\}/y/g'
ybyyby

The empty strings at the start and end matched, and the aa, and the remaining a.