Use sed to merge multiple lines

Hi all:

I have a file in which the contents are as following:

...
This is a test
ONE
TWO
Hello, world!
XXX YYY CCC
test again
three, four
five
six
seven
world
AAA BBB QQQ
test
eight, nine
world
FFF EEE KKK
...

I want to use sed to merge all lines between a line that contains a word 'test' and a line that contains a word 'world' into one line, and ignore other lines. In other words, I want a result as following:

This is a test ONE TWO Hello, world!
test again three, four five six seven world
test eight, nine world

Any help is appreciated. Thanks in advance for your help!

Sincerely,
Susan

Well, gets kind of tricky because of the arbitrary number of lines between "test" and "world", plus the arbitrary number of ines between "world" and "test"...
.,.. someone smarter than me will probably give you a better answer, but this works :slight_smile:

 sed 's/$/ @/' file.txt | sed -n '/test/,/world/p' | sed '/world/G' | sed -e :a -e '/@$/N; s/\@\n//; ta'

Awk can do it.

awk '/test/,/world/{ if($0~/world/) ORS="\n"; else ORS=" "; print}' filename

Sample output:
This is a test ONE TWO Hello, world!
test again three, four five six seven world
test eight, nine world

Thanks to both System Shock and vish indian! It seems there is no easy way for sed to do it. I have to use awk, perl, or something else ...