如何从 中获取输入read
,用空格分割单词,然后将这些单词放入数组中?
我想要的是:
$ read sentence
this is a sentence
$ echo $sentence[1]
this
$ echo $sentence[2]
is
(and so on...)
我用它来处理文本冒险的英语句子。
答案1
如果您正在使用bash
,它的read
命令有一个-a
选项。
从help read
Options:
-a array assign the words read to sequential indices of the array
variable ARRAY, starting at zero
所以
$ read -a s
This is a sentence.
请注意,结果数组的索引为零,因此
$ echo "${s[0]}"
This
$ echo "${s[1]}"
is
$ echo "${s[2]}"
a
$ echo "${s[3]}"
sentence.
$
答案2
与 @steeldriver 的类似回复
#!/bin/bash
printf "Input text:" && read UI ;
read -a UIS <<< ${UI} ;
X=0 ;
for iX in ${UIS[*]} ; do printf "position: ${X}==${iX}\n" ; ((++X)) ; done ;