获取bash数组中除了给定索引以外的所有元素。

huangapple go评论83阅读模式
英文:

getting all elements of a bash array except a given index

问题

  1. 团队,我有一个用例,需要在循环时将数组的余下部分保存到新数组中,新数组应该包含除了循环元素以外的所有元素。

$ a=(1 2 3 4 5)
$ b=()

for index in ${!a[@]}
do
b=(${a[@]:0:index} ${a[@]:index+1}) # 这样编写代码可以使其正常工作
echo ${b[@]}
done

  1. 每次迭代的预期循环值。

1 2 3 4
1 2 3 5
1 2 4 5
1 3 4 5
2 3 4 5

  1. <details>
  2. <summary>英文:</summary>
  3. Team, I have a use case to save remainder of array into new array while looping on its indices and new array should have all elements except the looped element.

$ a=(1 2 3 4 5)
$ b=()

for index in ${!a[@]}
do
b=(a - a[$index]) #how would i code his that it works ?
echo ${b[@]}
done

  1. expected loop values for each iteration.

1 2 3 4
1 2 3 5
1 2 4 5
1 3 4 5
2 3 4 5

  1. </details>
  2. # 答案1
  3. **得分**: 2
  4. 只保留简单。
  5. b=("{$a[@]}")
  6. 取消设置 b[$index]
  7. <details>
  8. <summary>英文:</summary>
  9. Just be simple.
  10. b=(&quot;${a[@]}&quot;)
  11. unset b[$index]
  12. </details>
  13. # 答案2
  14. **得分**: 0
  15. ```bash
  16. #!/bin/bash
  17. a=(1 2 3 4 5)
  18. b=()
  19. for index in "${!a[@]}" ; do
  20. b=("${a[@]:0:index}")
  21. # 这里应该是 "${a[@]:index+1:${#a[@]}-index-1}",
  22. # 但结果是相同的。
  23. b+=("${a[@]:index+1:${#a[@]}}")
  24. echo "${b[@]}"
  25. done
英文:

Use the parameter expansion with the :offset:length syntax:

  1. #!/bin/bash
  2. a=(1 2 3 4 5)
  3. b=()
  4. for index in &quot;${!a[@]}&quot; ; do
  5. b=(&quot;${a[@]:0:index}&quot;)
  6. # This should be &quot;${a[@]:index+1:${#a[@]}-index-1}&quot;,
  7. # but the result is the same.
  8. b+=(&quot;${a[@]:index+1:${#a[@]}}&quot;)
  9. echo &quot;${b[@]}&quot;
  10. done

huangapple
  • 本文由 发表于 2023年4月20日 06:48:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/76059342.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定