我在弄清楚如何在 shell 脚本中迭代空格分隔的单词/字符时遇到一些麻烦。例如,我想迭代一个包含字母表中由空格分隔的字符的变量。
注意:即使字母表变量包含空格分隔的字符串而不是字符,结果也应该是相同的,即“aa bb cc ...”而不是“a b c ..”
我已经尝试了很多提供的替代方案:如何在bash中将一行分成由一个或多个空格分隔的单词? https://stackoverflow.com/questions/1975849/how-to-split-a-line-into-words-separated-by-one-or-more-spaces-in-bash
Example:
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
预期/期望的输出:
1. a
2. b
3. c
and so on..
Result:
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
附加测试(未成功):
####################################################################
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
有人可以提供如何解决这个问题的解决方案(我更喜欢一个迭代字母表变量而不显式使用索引变量的解决方案,即 $alphabet[index] )?
感谢您的帮助。感谢您的反馈,我发现了该错误。
当我发布这个问题时,我认为这是无关紧要的,但我正在试验 .zshrc 文件中的函数。因此我使用(只是我的假设)zsh 解释器而不是sh 或bash 解释器。
通过意识到这可能是一个潜在的问题,我用谷歌搜索并发现了以下内容如何在 zsh 中一次一个单词地遍历字符串 https://stackoverflow.com/questions/23157613/how-to-iterate-through-string-one-word-at-a-time-in-zsh#23157823
所以我测试了以下内容并且它按预期工作:
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
NOTE:
index=$((++$index))
and/or
index=$(($index++))
在 zsh 中似乎没有像我预期的那样工作。
...我应该使用的小细节:
((++index))
or
((index++))
instead of
index=$((++$index))
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)