Finishing Up the Content Spinner

In fact, let's get rid of those superfluous debugging echo statements (actually, I always just comment them out instead by prepending # on each line, so that if I develop the script further, and things start to go sideways, I can simply uncomment the lines and figure out what's going on).

Here's the result:


$ sh spinner.sh spinme.txt
The
idea
is that each time you'd use a
word
you instead list a set of
synonyms
and the software automatically picks one
at random
and is done.

The magic really becomes apparent when the entire output is piped through the handy fmt command to put all the puzzle pieces back together on the line:


$ sh spinner.sh spinme.txt | fmt
The idea is that each time you'd use a word you instead list a set of
synonyms and the software automatically picks one randomly and is done.

Run it a second time, and it's the same concept being discussed, but the specific word choices are different:


$ sh spinner.sh spinme.txt | fmt
The idea is that each time you'd use a phrase you instead list a set of
alternative words and the software automatically picks one randomly and
is done.

So that's the program—mission accomplished.

Don't Bug Me, Man!

It turns out that there's a bug in the script; however, it's a subtle one that is nonetheless tricky to solve: if the text to spin includes a word cluster followed immediately by punctuation, the punctuation ends up being broken.

For example, consider if I slightly modified the spinme text like this:


The {idea|concept|inspiration} is that each time you'd
use a {word|phrase}, you instead list a
set of {similar words|synonyms|alternative words} and the
software automatically picks one
{randomly|at random} and is done.

See the added punctuation immediately after the word cluster on the second line? Here's what happens if I run this through the spinner script:


The inspiration is that each time you'd use a phrase , you instead list
a set of similar words and the software automatically picks one randomly
and is done.

See the problem? There shouldn't be a space before the comma. That's easily fixed with a sed statement, but it's an instance of a bigger problem, so rather than sed 's/ ,/,/g', I'm going to leave it to you, dear reader, to try to come up with a more generalized solution that takes into account all punctuation, including sequences like:


({cat|dog})

so that they'll be formatted properly in the final output.

And, that's a wrap for this article. For my next article, I'll look at, um, something or other. Perhaps it's time to start another game script?

______________________

Dave Taylor has been hacking shell scripts for over thirty years. Really. He's the author of the popular "Wicked Cool Shell Scripts" and can be found on Twitter as @DaveTaylor and more generally at www.DaveTaylorOnline.com.