Are sed matches always greedy?
I am trying to use sed to append an XML comment into an XML file as early as possible, which is right after the XML declaration if there is one. Something like this, in shell environment:
sed -e 's/\(<?xml[^?]*?>\)\?$/\1<!-- This is the new comment -->/'
I understand that sed wants to find the leftmost match and be as greedy as possible in the leftmost location where a match starts. However, the optional group doesn't match any XML declaration like this:
<?xml version="1.0" encoding="utf-8"?>
and instead it chooses to match an empty string, so the comment gets appended before the XML declaration. Why is that?
If I make the group mandatory, it matches as expected.