Saturday, October 24, 2009

Linux shuf command - generate random permutations


shuf - generate random permutations

Lets discuss the command line options available with Linux/UNIX 'shuf' command

From SHUF(1) man page:
1) -e, --echo
treat each ARG as an input line

$ shuf -e 3 5 6 7
7
6
5
3

$ shuf -e 3 5 6 7
7
5
6
3

$ shuf -e 3 5 6 7
3
6
5
7


2) -i, --input-range=LO-HI
treat each number LO through HI as an input line

To shuffle the numbers between 100 and 200

$ shuf -i 100-200

Also, 'shuf' command can be used along with UNIX/Linux 'seq' or 'jot' command to perform the same as shuf "-i" option.

$ shuf -e $(seq 100 200)
$ shuf -e $(jot 100 100)

3) -n, --head-lines=LINES
output at most LINES lines

$ shuf -i 100-200 -n 3
118
133
117

$ shuf -i 100-200 -n 3
193
188
145

To print a random word in Linux/UNIX

$ shuf -n 1 /usr/share/dict/words
disrupted

$ shuf -n 1 /usr/share/dict/words
festered

Note: /usr/share/dict/words is a standard file on UNIX like operating system and is a newline delimited list of dictionary words.

4) -o, --output=FILE
write result to FILE instead of standard output

$ shuf -n 3 /usr/share/dict/words -o /tmp/dict.txt
$ cat /tmp/dict.txt
heartlands
temple
unsatisfied

Also you can use UNIX/Linux redirection for the same

$ shuf -n 3 /usr/share/dict/words > /tmp/dict.txt

You can shuffle the lines of file and print the output to standard output like this

$ shuf < /tmp/file.txt

Related post:

- Generate random words in Linux in bash

No comments:

© Jadu Saikia www.UNIXCL.com