Bash
#!/bin/bash
output="";
until [ -n "$output" ];do
output=`echo John Jeff Emma Steve Julie|sed 's/ /\n/'|shuf|head -n1|sed '/[^a-zA-Z]/d;'`;
done
echo $output
Portability
This isn't entirely portable. It works on Ubuntu 14.04 with GNU bash 4.3.11, GNU coreutils 8.21 and GNU sed 4.2.2. In OpenBSD, according to @kernigh, the \n
escape in the regex replacements doesn't work properly, and shuf
doesn't exist.
Explanation
This makes extra checks to ensure that its output is valid. It initialises a variable to the empty string, then obtains random names for it with a loop. The loop loops until the variable is not empty. Unless the name chosen in any iteration is valid (only contains letters a-z
and A-Z
), the variable is set to the empty string, causing the loop to run again.
So, if the large command in the loop produces invalid output, it is discarded, until valid output is produced. It is then printed.
The central command echoes the five names separated by spaces to sed 's/ /\n/'
, which turns the spaces into newlines to be passed to shuf
, which shuffles the lines in its input (only operates on lines, hence the sed
command is needed, head -n1
, which takes the first one, and sed '/[^a-zA-Z]/d;'
, which discards any invalid input it receives.
The first sed
command doesn't have the g
switch; only one substitution is made. Then, there are only two options:
John
and Jeff Emma Steve Julie
. The latter is discarded later on. Sorry, John.