Shuffling Letters and Words

You can shuffle your feet and you can shuffle cards, but can you shuffle characters? Dave's latest column explores the possibilities.

My last few articles have described building a pretty sophisticated password generator, except for one thing: I never quite got to the point of scrambling the end result to add a second level of randomness. I sidestepped the issue by saying it was an exercise for the reader, but in fact, it's a pretty interesting problem, so let's look at it here.

You can reverse a word with the handy Linux command rev, like so:


$ echo "hello from the other side" | rev
edis rehto eht morf olleh

You also can reverse lines in a file so that the last line is shown first, penultimate line second, and so on:


$ cat -n test.me | sort -rn | cut -f2-
entering along with him.
enough to prevent a swirl of gritty dust from
glass doors of Victory Mansions, though not quickly
escape the vile wind, slipped quickly through the
chin nuzzled into his breast in an effort to
clocks were striking thirteen. Winston Smith, his
It was a bright cold day in April, and the

You recognize that opening paragraph even though it's backwards, right? "Clocks were striking thirteen" can only be George Orwell's cautionary tale 1984.

Note: there's a Linux command called tac that offers a reverse cat, which would do the job too, but I've always loved sort -rn as a command, so I wanted to demonstrate how to use it in a pipeline to accomplish the same result.

How about getting the lines of this file, but in completely random order? There's a command for that—at least in Linux: shuf. It's not available on the Mac OS X command line, however, so if you're playing along at home with your Mac system, well, you've just hit a road block. Sorry about that. I offer an alternative at the end of this article though, so don't despair!

If you're on a Linux system (and this is Linux Journal after all), then check this out:


$ cat test.me | shuf
clocks were striking thirteen. Winston Smith, his
entering along with him.
glass doors of Victory Mansions, though not quickly
escape the vile wind, slipped quickly through the
enough to prevent a swirl of gritty dust from
chin nuzzled into his breast in an effort to
It was a bright cold day in April, and the

So those commands are all ready to go, but how about scrambling letters in a line? That can be done with the shuf command as demonstrated previously, but individual lines aren't quite ready for the shuf treatment.

You can break up words by using the under-appreciated fold command, like this: