Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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:

0000110000000000

But I thought output would be:

0011000000000000

first occurrence of 00:

{00}00000000000000

second one:

0{00}0000000000000

and third one:

00{00}000000000000

Can someone explain what is happening?

share|improve this question
add comment

1 Answer

up vote 5 down vote accepted

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.

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.