我有一个包含许多单词的字符串,每个单词之间至少有一个空格。如何将字符串拆分成单独的单词,以便循环遍历它们?
字符串作为参数传递。例如,${2} == "cat cat file"
。我怎么才能遍历它?
另外,如何检查字符串是否包含空格?
发布于 2009-09-24 05:13:46
您是否尝试过将字符串变量传递给for
循环?例如,Bash将自动拆分为空格。
sentence="This is a sentence."
for word in $sentence
do
echo $word
done
This
is
a
sentence.
发布于 2012-11-16 00:52:59
我喜欢转换为数组,以便能够访问单个元素:
sentence="this is a story"
stringarray=($sentence)
现在您可以直接访问单个元素(从0开始):
echo ${stringarray[0]}
或者转换回字符串以进行循环:
for i in "${stringarray[@]}"
do
:
# do whatever on $i
done
当然,前面已经回答了直接遍历字符串的问题,但这个答案的缺点是不能跟踪单个元素以供以后使用:
for i in $sentence
do
:
# do whatever on $i
done
另请参见Bash Array Reference。
发布于 2009-09-25 16:15:32
只需使用内置的shell "set“即可。例如,
set $text
在那之后,$text中的单个单词将是$1、$2、$3等。
set -- junk $text
shift
处理$text为空或以破折号开头的情况。例如:
text="This is a test"
set -- junk $text
shift
for word; do
echo "[$word]"
done
这是打印
[This]
[is]
[a]
[test]
https://stackoverflow.com/questions/1469849
复制相似问题