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…

Bash: randomize data using the shuf command
Photo by Brett Jordan on Unsplash

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 <options

Example: 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 
5

To randomize the sequence just pipe the data to shuf

$ seq 1 5 | shuf 
2 
4 
1 
3 
5

You can even select a number of rows using the -n parameter

$ seq 1 5 | shuf -n2 
4 
1

Example: 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/words

Words 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's

conclusion

shuf is small, cute util that can be used in cases you want to randomize input, its very easy to use and understand.

Join Medium with my referral link - Konstantinos Patronas
As a Medium member, a portion of your membership fee goes to writers you read, and you get full access to every story…