How does backreferencing in the search pattern work in GNU Sed?

36 Views Asked by At

Given that

echo -e 'one.onetwo' | sed -n 's/\(.*\)\.\1/x/p'

prints xtwo, why does the following print onextwo?

echo -e 'one.two' | sed -n 's/\(.*\)\.\1/x/p'
1

There are 1 best solutions below

1
choroba On BEST ANSWER
echo -e 'one.two' | sed -n 's/\(.*\)\.\1/x/p'

The're only one place where \. can match: the dot between one and two. As there's no non-empty substring repeating before and after the dot, the .* matches the empty one. Then, the empty substring, the dot, and the repeated empty substring are replaced by x.

one ∅ . ∅ two
one ----- two
one   x   two