If I have something like:
echo 1 2 3 4 5 6
or
echo man woman child
what do I have to put behind the pipe to pick out one element of 1 2 3 4 5 6
or man woman child
?
echo 1 2 3 4 5 6 | command
3
If I have something like:
echo 1 2 3 4 5 6
or
echo man woman child
what do I have to put behind the pipe to pick out one element of 1 2 3 4 5 6
or man woman child
?
echo 1 2 3 4 5 6 | command
3
If your system has the shuf
command
echo 1 2 3 4 5 | xargs shuf -n1 -e
If the input doesn't really need to be echoed via standard input, then it would be better to use
shuf -n1 -e 1 2 3 4 5
If you don't have shuf (which is a great tool), but you do have bash, here's a bash-only version:
function ref { # Random Element From
declare -a array=("$@")
r=$((RANDOM % ${#array[@]}))
printf "%s\n" "${array[$r]}"
}
You'd have to reverse the sense of your call -- use ref man woman child
instead of echo man woman child | command
. Note that $RANDOM
may not be "strongly" random -- see Stephane's comments on: https://unix.stackexchange.com/a/140752/117549
Here's sample usage, and a random (!) sampling (the leading $
are the shell prompt; do not type them):
$ ref man woman child
child
$ ref man woman child
man
$ ref man woman child
woman
$ ref man woman child
man
$ ref man woman child
man
$ ref 'a b' c 'd e f'
c
$ ref 'a b' c 'd e f'
a b
$ ref 'a b' c 'd e f'
d e f
$ ref 'a b' c 'd e f'
a b
# showing the distribution that $RANDOM resulted in
$ for loop in $(seq 1 1000); do ref $(seq 0 9); done | sort | uniq -c
93 0
98 1
98 2
101 3
118 4
104 5
79 6
100 7
94 8
115 9
printf '%s\n' 1 2 3 4 5 | shuf -n1
(that is you feedshuf
the choices to pick from one per line). – Stéphane Chazelas Mar 15 '16 at 17:58