Hen*_*rik 4 iteration shell zsh
我在弄清楚如何在 shell 脚本中迭代空格分隔的单词/字符时遇到了一些麻烦。例如,我想迭代一个变量,该变量包含字母表中由空格分隔的字符。
注意:即使字母表变量包含空格分隔的字符串而不是字符,结果也应该相同,即“aa bb cc ...”而不是“abc ..”
我已经尝试了很多提供的替代方法: How to split a line into words in bash in a or more space?
示例:
local alphabet="a b c d e f g h i j k l m n o p q r s t u v w x y z"
local index="0"
for character in $alphabet; do
index=$((++index))
echo "$index. $character"
# Possibility to do some more stuff
done
Run Code Online (Sandbox Code Playgroud)
预期/期望输出:
1. a
2. b
3. c
and so on..
Run Code Online (Sandbox Code Playgroud)
结果:
1. a b c d e f g h i j k l m n o p q r s t u v w x y z
Run Code Online (Sandbox Code Playgroud)
额外的测试(没有成功):
####################################################################
local alphabet="a b c d e f g h i j k l m n o p q r s t u v w x y z"
local index="0"
for character in ${alphabet[@]}; do
index=$((++index))
echo "$index. $character"
# Possibility to do some more stuff
done
####################################################################
local alphabet="a b c d e f g h i j k l m n o p q r s t u v w x y z"
local alphabetArray=( ${alphabet} )
local index="0"
for character in "${alphabetArray[@]}"; do
index=$((++index))
echo "$index. $character"
# Possibility to do some more stuff
done
####################################################################
local alphabet="a b c d e f g h i j k l m n o p q r s t u v w x y z"
local alphabetArray=( ${alphabet} )
local index="0"
for character in ${alphabetArray}; do
index=$((++index))
echo "$index. $character"
# Possibility to do some more stuff
done
Run Code Online (Sandbox Code Playgroud)
有人可以提供有关如何解决此问题的解决方案(我更喜欢在不显式使用索引变量的情况下迭代字母表变量的解决方案,即 $alphabet[index] )?
谢谢你的帮助。由于您的反馈,我发现了错误。
当我发布这个问题时,我认为这无关紧要,但我正在试验我的 .zshrc 文件中的函数。因此我使用(只是我的假设)zsh 解释器而不是 sh 或 bash 解释器。
通过意识到这可能是一个潜在的问题,我用谷歌搜索并找到了以下如何在 zsh 中一次迭代一个单词
所以我测试了以下内容,它按预期工作:
setopt shwordsplit
local alphabet="a b c d e f g h i j k l m n o p q r s t u v w x y z"
local index="0"
for character in $alphabet; do
index=$(($index+1))
echo "$index. $character"
# Possibility to do some more stuff
done
unsetopt shwordsplit
Run Code Online (Sandbox Code Playgroud)
笔记:
index=$((++$index))
and/or
index=$(($index++))
Run Code Online (Sandbox Code Playgroud)
在 zsh 中似乎没有我预期的那样工作。
... 小细节,我应该使用:
((++index))
or
((index++))
instead of
index=$((++$index))
Run Code Online (Sandbox Code Playgroud)