ProgrammingThis forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.
Notices
Welcome to LinuxQuestions.org, a friendly and active Linux Community.
You are currently viewing LQ as a guest. By joining our community you will have the ability to post topics, receive our newsletter, use the advanced search, subscribe to threads and access many other special features. Registration is quick, simple and absolutely free. Join our community today!
Note that registered members see fewer ads, and ContentLink is completely disabled once you log in.
bash only does one dimensional arrays. To get really sophisticated with arrays you're best off using Perl.
Having said that you could do an array with the declare built in.
Example:
Say you have a text file named "test" with the following two lines:
Code:
the quick brown fox jumped over the lazy dog
now is the time for all good men to come to the aid of their country
You could create the following simple script:
Code:
#!/bin/bash
declare -a arrtest
arrtest=(`cat test`)
echo ${arrtest[13]}
The above would make an array named "arrtest" (the delcare -a line). It would then be told to contain all the words of the two lines in the file "test" as individual elements (the arrtest= line). The last line of the script would print the 13th element which would be the word "time" from the second line of the file. (The element numbers start at 1 and count from there. The [13] is called a subscript of the array arrtest.
What you want to do is go in a loop, assign each line to one element of array & keep incrementing the subscripts. The way to assign some value to to the nth subscript of array arr is:
The problem is that the poster wants random "line" instead of words. The code may not remain that small if you want to dispaly randomly selected full line using arrays.
@vivekr: I'm sure your code does the job. I was just wishfully wondering aloud about doing it using array in a "clever & small" shell script. Billy did it in "perl" anyway.
LinuxQuestions.org is looking for people interested in writing
Editorials, Articles, Reviews, and more. If you'd like to contribute
content, let us know.