如何在shell中循环多个逗号分隔的字符串

发布于 2025-01-10 20:22:07 字数 235 浏览 0 评论 0原文

我正在尝试循环遍历多个逗号分隔的字符串,其中字符串中的逗号数量相同。

我已经尝试过下面的代码片段,但它没有返回任何内容。

#!/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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

猫性小仙女 2025-01-17 20:22:07

尽快将逗号分隔的字符串替换为数组。如果它是一个硬编码的字符串,那就很简单了:

ip1=(Ok1 ok2 ok3)

如果它来自外部源(例如,命令行参数或从文件中读取),请使用read

ip1s="Ok1,ok2,ok3"
IFS=, read -a ip1 <<< "$ips1"

一旦你有了一个数组,你就可以使用数组语法进行迭代:

for i in "${ip1[@]}"; do
    echo "$i"
done

如果您有多个数组想要以锁步方式迭代,您可以迭代数组的键:(

for i in "${!ip1[@]}"; do
  echo "${ip1[i]}"
  echo "${ip2[i]}"
done

这忽略了稀疏数组的可能性,但您必须努力获取这些数组。在实践中,数组和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:

ip1=(Ok1 ok2 ok3)

If it's from an external source (say, a command-line argument or read from a file), use read:

ip1s="Ok1,ok2,ok3"
IFS=, read -a ip1 <<< "$ips1"

Once you have an array, you can use array syntax for iteration:

for i in "${ip1[@]}"; do
    echo "$i"
done

If you have multiple arrays you want to iterate in lockstep, you can iterate over the keys of the arrays:

for i in "${!ip1[@]}"; do
  echo "${ip1[i]}"
  echo "${ip2[i]}"
done

(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.)

柏拉图鍀咏恒 2025-01-17 20:22:07

修复:

  1. ip 更改为 ip1ip2
  2. 将智能引号更改为常规引号:
  3. 将逗号替换为空格,在最后的 / 后添加一个空格
ip1="Ok1,ok2,ok3"
ip2="ty1,ty2,ty3"
    
for i in ${ip1//,/ }
do 
        echo "$i"
done

最好使用数组,这样项目就会自然地分隔开来,并且您不必进行任何字符串操作。

ip1=(Ok1 ok2 ok3)
ip2=(ty1 ty2 ty3)
    
for i in "${ip1[@]}"
do 
        echo "$i"
done

Fixes:

  1. Change ip to ip1 or ip2
  2. Change the smart quotes to regular quotes: "
  3. Replace the commas with spaces by adding a space after the final /
ip1="Ok1,ok2,ok3"
ip2="ty1,ty2,ty3"
    
for i in ${ip1//,/ }
do 
        echo "$i"
done

It would be better to use arrays, then the items would be naturally separated and you wouldn't have to do any string manipulation.

ip1=(Ok1 ok2 ok3)
ip2=(ty1 ty2 ty3)
    
for i in "${ip1[@]}"
do 
        echo "$i"
done
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文