bash 循环包含空格的字符串集
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18383291/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Loop over set of strings containing spaces
提问by jolivier
I have multiple strings like "a b", "c d", "foo bar" and so on. I want to loop over this set of string and perform an action on each of these. In this action I call multiple other scripts so I do not want to change IFS for this loop since it could break my invocation of other scripts. This is why I try to escape the spaces contained in these strings but without success.
我有多个字符串,如“a b”、“c d”、“foo bar”等。我想遍历这组字符串并对每个字符串执行一个操作。在此操作中,我调用了多个其他脚本,因此我不想更改此循环的 IFS,因为它可能会中断我对其他脚本的调用。这就是为什么我试图转义这些字符串中包含的空格但没有成功。
So for instance I expect to get
所以例如我希望得到
a b
c d
And I tried the following:
我尝试了以下方法:
#!/bin/sh
x="a b"
y="c d"
echo "Attempt 1"
all="$x $y"
for i in $all ; do
echo $i
done
echo "Attempt 2"
all="a\ b c\ d"
for i in $all ; do
echo $i
done
echo "Attempt 3"
all=($x $y)
for i in ${all[@]} ; do
echo $i
done
echo "Attempt 4"
all='"'$x'" "'$y'"'
for i in $all ; do
echo $i
done
echo "Attempt 5"
for i in "$x" "$y" ; do
echo $i
done
echo "Attempt 6"
all2=("a b" "c d");
for i in ${all2[@]}; do
echo $i
done
echo "Attempt 7"
all3="a b c d"
echo $all3|
while read i; do
echo $i
done
Only attempt 5 succeeds, but I would like to do this without having to declare one variable per string, (it would be painful to maintain). I just introduced x and y for testing but the idea is to declare in one variable the set "a b" and "c d".
只有尝试 5 成功,但我想这样做而不必为每个字符串声明一个变量,(维护起来会很痛苦)。我刚刚介绍了 x 和 y 进行测试,但想法是在一个变量中声明集合“a b”和“c d”。
回答by fedorqui 'SO stop harming'
You need to wrap variables within double quotes, both in all=("$x" "$y")
and "${all[@]}"
:
您需要将变量括在双引号内,包括 inall=("$x" "$y")
和"${all[@]}"
:
x="a b"
y="c d"
echo "Attempt XX"
all=("$x" "$y")
for i in "${all[@]}" ; do
echo "$i"
done
Executing it returns:
执行它返回:
Attempt XX
a b
c d
Update
更新
To avoid using a different variable for each string, do the following:
要避免为每个字符串使用不同的变量,请执行以下操作:
all=("a b" "c d")
for i in "${all[@]}" ; do
echo "$i"
done
回答by Adrian Frühwirth
Your problem is lack of quoting. Without quoting, word splitting occurs:
你的问题是缺乏引用。没有引用,就会发生分词:
$ x="a b"; y="c d"; all=("$x" "$y"); for i in "${all[@]}"; do echo "$i"; done
a b
c d
Using an array is the most elegant solution, and, of course, x
and y
are superfluous. You can just as well do:
使用阵列是最好的解决方法,以及,当然,x
并y
都是多余的。你也可以这样做:
$ all=("a b" "c d"); for i in "${all[@]}"; do echo "$i"; done
a b
c d