
どのように入力を受け取り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 ;