如何在shell中循环多个逗号分隔的字符串
我正在尝试循环遍历多个逗号分隔的字符串,其中字符串中的逗号数量相同。
我已经尝试过下面的代码片段,但它没有返回任何内容。
#!/bin/bash
ip1=“Ok1,ok2,ok3”
ip2=“ty1,ty2,ty3”
for i in ${ip[@]//,/}
do
echo $i
done
有人可以建议我如何改变这一点吗?
I’m trying to loop through multiple comma separated strings with same number of commas in the string.
I’ve tried the below snippet but it doesn’t return anything.
#!/bin/bash
ip1=“Ok1,ok2,ok3”
ip2=“ty1,ty2,ty3”
for i in ${ip[@]//,/}
do
echo $i
done
Could someone please suggest how I can change this.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
尽快将逗号分隔的字符串替换为数组。如果它是一个硬编码的字符串,那就很简单了:
如果它来自外部源(例如,命令行参数或从文件中读取),请使用
read
:一旦你有了一个数组,你就可以使用数组语法进行迭代:
如果您有多个数组想要以锁步方式迭代,您可以迭代数组的键:(
这忽略了稀疏数组的可能性,但您必须努力获取这些数组。在实践中,数组和
n
个元素通常具有键 0、1、...n
-1。)Replace the comma-separated string with an array as soon as feasible. If it's a hard-coded string, that's trivial:
If it's from an external source (say, a command-line argument or read from a file), use
read
:Once you have an array, you can use array syntax for iteration:
If you have multiple arrays you want to iterate in lockstep, you can iterate over the keys of the arrays:
(This ignores the possibility of sparse arrays, but you have to work to get those. In practice, arrays with
n
elements usually have keys 0, 1, ...n
-1.)修复:
ip
更改为ip1
或ip2
“
→”
/
后添加一个空格最好使用数组,这样项目就会自然地分隔开来,并且您不必进行任何字符串操作。
Fixes:
ip
toip1
orip2
“
→"
/
It would be better to use arrays, then the items would be naturally separated and you wouldn't have to do any string manipulation.