【问题标题】:Bash compose new array with the ordered input of other arraysBash 用其他数组的有序输入组成新数组
【发布时间】:2015-11-22 17:05:23
【问题描述】:

我正在尝试生成一个新数组,结合其他数组,尊重特定序列。在纯 Bash 中。 示例:

numbers=(0 1 2 3 4 5 6 7 8);

colors=(red blue green);

loop_sequence=(numbers numbers colors numbers colors colors)

输出示例:

0
1
red
2
blue
green
3
4
red
5
blue
green
6
7
red
8
blue
green
0
1
red
2
blue
green...

但我发现很难进行迭代的内部循环。 非常欢迎任何帮助。

【问题讨论】:

标签: arrays bash loops


【解决方案1】:

你可以使用这个脚本:

numbers=(0 1 2 3 4 5 6 7 8)
colors=(red blue green)
loop_sequence=(numbers numbers colors numbers colors colors)    
numLen=${#numbers[@]}
colLen=${#colors[@]}

arr=() # output array
max=3 # max counter
for ((r=0; r<max; r++)); do
   for i in "${loop_sequence[@]}"; do
      [[ $i == numbers ]] && arr+=("${numbers[$((n++ % numLen))]}") ||
             arr+=("${colors[$((c++)) % colLen]}")
   done
done

printf "%s\n" "${arr[@]}"

输出:

0
1
red
2
blue
green
3
4
red
5
blue
green
6
7
red
8
blue
green

【讨论】:

  • 在 debian, bash 4 上,我得到:声明:-n:无效选项
  • declare -nbash 4.3 的新成员
  • @Fredfs:检查更新的答案。它也应该适用于旧 BASH 版本。
  • 为什么你的“最大计数器”设置为 3?
  • 这只是一个示例值。将其设置为您想要的任何数字。
猜你喜欢
  • 2017-07-11
  • 1970-01-01
  • 2017-09-17
  • 2020-11-30
  • 1970-01-01
  • 1970-01-01
  • 2018-12-04
  • 2020-03-11
  • 1970-01-01
相关资源
最近更新 更多