Chi Shin Hsu
Chi Shin Hsu

Reputation: 273

Sed replace all matches after some patterns

I want to replace all B after '='.

echo A, B = A B B A B B B | sed 's/=\(.*\)B\(.*\)/=\1C\2/g'

The expected result should be

A, B = A C C A C C C

But I got this result:

A, B = A B B A B B C

Only the last matched pattern be replaced. How to resolve it?

Upvotes: 0

Views: 88

Answers (2)

NeronLeVelu
NeronLeVelu

Reputation: 10039

Same kind of idea as @sat but starting from beginning of string

sed -e ':cycle' -e 's/\(.*=.*\)B/\1C/;t cycle'

posix compliant so should works on any sed

Upvotes: 0

sat
sat

Reputation: 14979

Use this sed:

sed ':loop; s/\(=.*\)B\(.*\)/\1C\2/; t loop'

Test:

$ echo A, B = A B B A B B B | sed ':loop; s/\(=.*\)B\(.*\)/\1C\2/; t loop'
A, B = A C C A C C C

Upvotes: 2

Related Questions