I am trying to write a shell script. The idea is to select a single line at random from text file and display it as an Ubuntu desktop notification.
But I want different lines to be selected each time I execute the script. Is there any solution to do this? I don't want the entire script. Just that simple thing only.
You can use
shuf
utility to print random lines from file-n
: number of lines to printExamples:
You can also use
sort
command to get random line from the file.Just for fun, here is a pure bash solution which doesn't use
shuf
,sort
,wc
,sed
,head
,tail
or any other external tools.The only advantage over the
shuf
variant is that it's slightly faster, since it's pure bash. On my machine, for a file of 1000 lines theshuf
variant takes about 0.1 seconds, while the following script takes about 0.01 seconds ;) So whileshuf
is the easiest and shortest variant, this is faster.In all honesty I would still go for the
shuf
solution, unless high efficiency is an important concern.Say you have file
notifications.txt
. We need to count total number of lines, to determine range of random generator:Lets write to variable:
Now to generate number from
0
to$LINE
we will useRANDOM
variable.Lets write it to variable:
Now we only need to print this line number:
About RANDOM:
Be sure your file have less then 32767 line numbers. See this if you need bigger random generator that works out of the box.
Example:
Here's a Python script that selects a random line from input files or stdin:
The algorithm is O(n)-time, O(1)-space. It works for files larger than 32767 lines. It doesn't load input files into memory. It reads each input line exactly once i.e., you can pipe arbitrary large (but finite) content into it. Here's an explanation of the algorithm.
I'm impressed by the work that Malte Skoruppa and others did, but here is a much simpler "pure bash" way to do it:
As some have noted, $RANDOM is not random. However, the file size limit of 32767 lines is overcome by stringing $RANDOMs together as needed.