I have the following text:
A
Hello
world
B
Hello
world
C
Hello
world
I know that I can replace Hello
by Hi
using sed
:
sed 's/Hello/Hi/g' -i test
but this replace each Hello
with Hi
:
A
Hi
world
B
Hi
world
C
Hi
world
what I really want is to replace only the Hello
after B
:
A
Hello
world
B
Hi
world
C
Hello
world
so I have tried this:
sed 's/"B\nHello"/"B\nHi"/g' -i test
but nothing happened, How can I do this?
Note: There are some white-spaces on the beginning of each line of the file.
Best Answer
Something like:
That assumes there are no consecutive
B
s (oneB
line followed by anotherB
line).Otherwise, you could do:
The
sed
equivalent would be:To replace the second word after
B
, or to replaceworld
withuniverse
only if two lines above containedB
:To generalise it to
n
lines above: