works fine, but the words should not be in a function or hard coded... and tbh i am not what i need to do, to create a word randomly, and sed and awk are out of question as well.
what can be used instead of sed, as i dont know anything about sed and rather learn shell scripting first and then look at sed, also just so i can understand this better, the random word file, needs to one word per line and numbered for this to work??
You can store all the words in a file (assume words.txt).
stored_word()
{
if [ -z "$stored_words_count" ]
then
stored_words_count=$(wc -l < words.txt)
fi
number=$RANDOM
let "number = number % stored_words_count + 1"
tail +$number words.txt | head -1
}
Another solution is to read the file into an array.
init_stored_words()
{
while read w
do
words[${#words[@]}]=$w
done < words.txt
stored_words_count=${#words[@]}
}
stored_word()
{
[ -z "$stored_words_count" ] && init_stored_words
number=$RANDOM
let "number %= stored_words_count"
echo ${words[$number]}
}
1.Do you mean that how str get the word from file?
While loop reads file line by line and str variable receive the word read from file
2.For each line read from file, variable no is decremented and when its value reaches zero, we reached the desired line in the file and assign value read to variable word and exit the loop.