Inactive Tutor answered 06/30/26
One of the easiest ways is using the `shuf` command. If you only want to read one random line from a specific file, the command you need to run is this:
To break this down:
- shuf is a binary which generates random permutations, writing the input line(s) to standard output.
- -n <#> is an option or switch which designates the output at most COUNT lines. It requires a number, so in our case, we specify 1. You do not include `<` or `>`, just the number.
- file.txt is our imaginary file that we're reading. In a real example, you'll need to specify which file is being read from.
If you're running an older system or you don't have shuf available, you have another easy option as well, which takes two different commands (sort and head).
- sort will write sorted concatenation of all FILE(s) to standard output.
- `-R` forces sort to randomly shuffle, grouping by identical keys. Not perfect, but it'll get the job done. This means `a` is grouped with `a`, `b` is grouped with `b`, etc.
- file.txt is again our arbitrary file which you would replace with the file you're sorting/reading from.
- | is used to pipe the output from the first command (`sort -R file.txt`) into our next set of instructions.
- head, by default, reads the first 10 lines of a file and prints them to standard output.
- `-n <#>` will override the default of 10 lines to whatever you specify. So, in our example, we are only reading 1 line.
Quick note: This isn't the most memory-efficient way, and using awk would probably be better, but this states to do things easily... so that's what we'll do!