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?

2
  • 1
    dump whatever you 'cooked' and we shall see how to improve it Commented Nov 10, 2009 at 7:52
  • what actual problem are you solving? Commented Nov 10, 2009 at 7:53

2 Answers 2

1

Here's another way:

for ((i=1; i<=${#ar[@]}; i++ ))
do
    ar_new+=("${ar[*]:0:$i} ")
done
Sign up to request clarification or add additional context in comments.

1 Comment

Sweet exactly what I was looking for (some manipulation with bash variable itself)
0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.