Bash: randomize data using the shuf command
We all know how to sort data using the sort command, but how we can achieve the opposite? to randomize data comming from stdin or a file…
We all know how to sort data using the sort command, but how we can achieve the opposite? to randomize data comming from stdin or a file? there is the not so well known command shuf lets see how it works.
The shuf command should be installed by default on most Linux distros, shuf can read input either from stdin or a file like that.
$ cat file | shuf <options>or
$ shuf file <optionsExample: randomizing a sequence of numbers
seq can create a sequence of numbers, the syntax is pretty easy seq <start> <stop>
$ seq 1 5
1
2
3
4
5To randomize the sequence just pipe the data to shuf
$ seq 1 5 | shuf
2
4
1
3
5You can even select a number of rows using the -n parameter
$ seq 1 5 | shuf -n2
4
1Example: working with files
Its not very different than working with shuf from stdin but lets see an example, in linux there is a dictionary of words in
/usr/share/dict/wordsWords in this file are sorted, to select 10 random words from this file run shuf like this
$ shuf /usr/share/dict/words -n10
ombudsman
insurmountable
Kirghiz's
pariahs
fib's
flanges
photographically
multifariousness's
sternness's
grasp'sconclusion
shuf is small, cute util that can be used in cases you want to randomize input, its very easy to use and understand.