Being able to select random lines from a file in Linux can be very helpful and convenient. There are a few easy ways to do this, including using the
shuf utilty. shuf is included on many Linux/Unix systems as part of GNU coreutils. GNU coreutils can be easily installed if not already.
Selecting Random Lines with shuf
The examples below show some common ways to use
shuf to randomize lines in a file or from standard input in Linux.
# shuffle all lines from sample file
# shuffle all lines from standard input
cat sample_data_1.txt | shuf sample_data_1.txt
# select 10 random lines from sample file using -n
shuf sample_data_1.txt -n 10
# use -r to allow records to potentially be selected more than once (repeated)
shuf -r sample_data_1.txt
# randomly select each line in file twice using -r and -n (n twice as large as file or standard input)
shuf -n 2000 -r sample_data_1.txt