开发者

How to randomize lines read from a file into an array and loop over array in bash script [duplicate]

开发者 https://www.devze.com 2023-01-30 14:20 出处:网络
This question already has answers here: How can I shuffle the lines of a text file on the Unix command line or in a shell script?
This question already has answers here: How can I shuffle the lines of a text file on the Unix command line or in a shell script? (19 answers) 开发者_开发问答 Closed 8 years ago.

I have a text file which contains famous quotations.

I want to write a bash shell script that does the following:

  1. reads all the lines of the file into an array (each line is an array entry)
  2. 'Shuffles' or randomizes the array positions
  3. 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
0

精彩评论

暂无评论...
验证码 换一张
取 消