tags:

views:

106

answers:

2

So if I have a bash array:

ar=( "one" "two" "three" "four")

What is the best way to make a new array such that it looks like this:

ar-new=( "one" "one two" "one two three" "one two three four" )

I cooked up something that use a for loop inside a for loop and using seq. Is there a better/more elegant way to accomplish this?

A: 

Depending on what, exactly, you are trying to accomplish, you can do it in one loop without any external commands.

Using an arithmetic for loop:

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

Using a string for loop loop (might not work for large arrays?, might be slower for large arrays):

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
Chris Johnsen
+1  A: 

Here's another way:

for ((i=1; i<=${#ar[@]}; i++ ))
do
    ar_new+=("${ar[*]:0:$i} ")
done
Dennis Williamson
Sweet exactly what I was looking for (some manipulation with bash variable itself)
polyglot