Here is a sed command. I want to substitute third occurrence of 00 to 11

echo "0000000000000000" | sed -e 's/00/11/3'

The output is:


But I thought output would be:


first occurrence of 00:


second one:


and third one:


Can someone explain what is happening?

1 Answer 1


When a sed regex pattern has been matched, its next search starts from immediately after the just matched pattern... To do what you want, you need something like perl's regex Look-Ahead and Look-Behind Zero-width Assertions.

In your case, you want to assert (check) that a sub-pattern (the 2nd 0) does exist after the 1st 0 of your overall-pattern. The sub-pattern is treated as having zero-width, and so when the overall-pattern is matched, the search continues from immediately after the 1st part of the pattern, namely, after your first zero 0.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .