5

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?

1 Answer 1

5

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 .