我要逐行读取文件,如下所示:
while read line;
do
set -- $line
c=$# #count words and save as $c
r=$(( RANDOM%c ))
#here i'd like to get the word on position r from $line
done < words.txt
我知道,我可以得到如下单词1:
set -- $line
echo $1
但是如何用$ r中保存的整数替换1?
答案 0 :(得分:1)
答案 1 :(得分:1)
改为使用array:
words=($line)
echo "${words[$r]}"
例如:
$ var words
declare -a words='([0]="a" [1]="b" [2]="c")'
$ v=2
$ echo "${words[v]}"
c
$ echo "${words[v-1]}"
b