ZSHで文字列をスペースに分割する

ZSHで文字列をスペースに分割する

一方file.txt:

first line
second line
third line

これは以下に適用されますbash

while IFS=' ' read -a args; do
  echo "${args[0]}"
done < file.txt

生産

first
second
third

つまり、ファイルを 1 行ずつ読み取ることができ、各行でスペースを区切り文字として使用して、行をさらに配列に分割できます。ただし、zsh結果はerror:ですread: bad option: -a

zshで同じ目標を達成するにはどうすればよいですかbash?いくつかの解決策を試しましたが、解決できませんでした。スペースを区切り文字として文字列を配列に分割する

ベストアンサー1

~からman zshbuiltins、zshの読み取りが-A代わりに使用されます。

read [ -rszpqAclneE ] [ -t [ num ] ] [ -k [ num ] ] [ -d delim ]
     [ -u n ] [ name[?prompt] ] [ name ...  ]
...
       -A     The  first  name  is taken as the name of an array
              and all words are assigned to it.

だからコマンドは

while IFS=' ' read -A args; do
  echo "${args[1]}"
done < file.txt

デフォルトでは、zsh配列番号はで始まり、1bash配列番号はで始まります0

$ man zshparam
...
Array Subscripts
...
The elements are numbered  beginning  with  1, unless the
KSH_ARRAYS option is set in which case they are numbered from zero.

おすすめ記事