鉴于file.txt
:
first line
second line
third line
这适用于bash
:
while IFS=' ' read -a args; do
echo "${args[0]}"
done < file.txt
生产
first
second
third
也就是说,我们能够逐行读取文件,并且在每一行上,我们使用空格作为分隔符将行进一步拆分为数组。但在 中zsh
,结果是错误:read: bad option: -a
。
我们怎样才能实现zsh
与 in 相同的目标bash
?我尝试了多种解决方案,但始终无法解决使用空格作为分隔符将字符串拆分为数组。
答案1
从man zshbuiltins
,zsh的read使用-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 数组编号以 开头1
,而 bash 则以 开头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.