循环遍历包含空格的字符串集 [英] Loop over set of strings containing spaces

查看:58
本文介绍了循环遍历包含空格的字符串集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有多个字符串,例如"ab","cd","foo bar"等等.我想遍历这组字符串,并对每个字符串执行一个操作.在此操作中,我调用了多个其他脚本,因此,我不想为此循环更改IFS,因为它可能会破坏我对其他脚本的调用.这就是为什么我尝试转义这些字符串中包含的空格但没有成功的原因.

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

我尝试了以下操作:

#!/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 

只有尝试5成功,但是我想这样做而不必为每个字符串声明一个变量(维护起来很痛苦).我刚刚介绍了x和y进行测试,但想法是在一个变量中声明集合"ab"和"cd".

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".

推荐答案

您需要将变量用双引号引起来,都用 all =("$ x""$ y")"$ {all [@]}" :

You need to wrap variables within double quotes, both in all=("$x" "$y") and "${all[@]}":

x="a b"
y="c d"

echo "Attempt XX"
all=("$x" "$y")
for i in "${all[@]}" ; do
  echo "$i"
done

执行它会返回:

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

这篇关于循环遍历包含空格的字符串集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆