如何從 中取得輸入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 ;