![ZSH中按空格分割字符串](https://linux22.com/image/148145/ZSH%E4%B8%AD%E6%8C%89%E7%A9%BA%E6%A0%BC%E5%88%86%E5%89%B2%E5%AD%97%E7%AC%A6%E4%B8%B2.png)
鉴于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.