所以,如果我有一个bash数组:使bash的阵列从逐步增加另一个阵列
ar=("one" "two" "three" "four")
是什么力量让一个新的阵列,使得它看起来像这样的最佳方式:
ar-new=("one" "one two" "one two three" "one two three four")
我编写了一些在for循环中使用for循环并使用seq
的东西。有没有更好/更优雅的方式来完成这一点?
所以,如果我有一个bash数组:使bash的阵列从逐步增加另一个阵列
ar=("one" "two" "three" "four")
是什么力量让一个新的阵列,使得它看起来像这样的最佳方式:
ar-new=("one" "one two" "one two three" "one two three four")
我编写了一些在for循环中使用for循环并使用seq
的东西。有没有更好/更优雅的方式来完成这一点?
这里的另一种方式:
for ((i=1; i<=${#ar[@]}; i++))
do
ar_new+=("${ar[*]:0:$i} ")
done
甜到底我在找什么(用bash变量本身进行一些操作) – polyglot 2009-11-10 17:40:18
根据你正在尝试完成的内容,你可以在一个循环内完成而不需要任何外部命令。
使用算术for
循环:
typeset -a ar
ar=("one" "two" "three" "four")
typeset -a ar_new=()
p=""
for ((i=0; i < ${#ar[@]}; ++i)); do
p="$p${p:+ }${ar[$i]}"
ar_new[$i]="$p"
done
使用字符串for
循环回路(可能不适合大型阵列工作?可能是大型阵列较慢):
typeset -a ar
ar=("one" "two" "three" "four")
typeset -a ar_new=()
p=""
for s in "${ar[@]}"; do
p="$p${p:+ }$s"
ar_new=("${ar_new[@]}" "$p")
done
转储无论你“熟”,我们将看到如何改善它 – 2009-11-10 07:52:19
你解决了什么实际问题? – ghostdog74 2009-11-10 07:53:27