首页 > 解决方案 > 如何从字符串中获取单词 x

问题描述

我想逐行读取文件,如下所示:

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

但是如何将 1 替换为保存在 $r 中的整数?

标签: bashsh

解决方案


使用间接

echo "${!r}"

例如:

$ set -- a b c
$ echo $2
b
$ v=2
$ echo ${!v}
b

推荐阅读