How to randomize lines read from a file into an array and loop over array in bash script [duplicate]
I have a text file which contains famous quotations.
I want to write a bash shell script that does the following:
- reads all the lines of the file into an array (each line is an array entry)
- 'Shuffles' or randomizes the array positions
- Loops over the 'randomized' array and prints the current line
I am new to bash scripting. Can anyone show me how to do this?
I am running on Linux Ubuntu.
This is what I have at the moment:
while read -r -a array
do
print "${array[@]}"
done < myfile.txt
I need to randomize the read lines. Anyone knows how I can modify the script to do what I want?
I tried using sort --random-sort like this:
done < cat myfile.txt | sort --random-sort
But bash issued error messages
You can use the fortune
program. You may have to modify your file to include the required delimiters.
To fix the error message:
done < <(sort --random-sort myfile.txt)
or
sort --random-sort myfile.txt | while
精彩评论