Search code examples
sedbackreferencegnu-sed

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


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'

Solution

  • 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