Sasha, you helped in a subtle indirect way.
I decided to perform the same exercise as you. I created a text file and a new script. Worked as expected.
I then slowly expanded the new script with snippets from the problematic script. Everything kept working as expected.
Serious head scratching time.
I don't know what finally motivated me to check, but somewhere in the deep chasms of my mind I decided to check the end-of-line usage in the several text files I was extracting and modifying text. Okay, you probably can guess the remainder of the story now.
The text files all used Windows/DOS end-of-line terminations rather than 'nix.
I manually changed the text files to 'nix style and then my problematic script no longer was problematic. The inline modifications with sed worked as expected.
So in the original script I converted the end-of-line usage on-the-fly with the fromdos command.
My script now works like I intended several hours ago.
Who would have guessed?
What an awful way to spend several hours!