3

I have 4 arrays:

ARRAY1=( A B C D )
ARRAY2=( E F G )
ARRAY3=( H I J K L M )
ARRAY4=( N )

Some how I would like to get a new array with these elements in it:

FINAL_ARRAY=( ARRAY1 A ARRAY1 B ARRAY1 C ARRAY1 D ARRAY2 E ARRAY2 F ARRAY2 G ARRAY3 H ARRAY3 I ARRAY3 J ARRAY3 K ARRAY3 L ARRAY3 M ARRAY4 N )

Can this be done using some kind of for loop or any other way in BASH?

Thanks.

1
  • 2
    You really shouldn't be turning variable names (code) into data. Do you make a habit of putting your C variable names in C string values too? Commented Jun 5, 2013 at 0:52

1 Answer 1

8
#!/bin/bash
ARRAY1=( A B C D )
ARRAY2=( E F G )
ARRAY3=( H I J K L M )
ARRAY4=( N )
ARRAYNAMES=(ARRAY1 ARRAY2 ARRAY3 ARRAY4)
for an in "${ARRAYNAMES[@]}"; do
    aref="$an[@]"
    for item in "${!aref}"; do
        NEWARRAY=("${NEWARRAY[@]}" "$an" "$item")
    done
done
echo "${NEWARRAY[@]}"

Output:

ARRAY1 A ARRAY1 B ARRAY1 C ARRAY1 D ...
Sign up to request clarification or add additional context in comments.

3 Comments

bang on. That's it. Thanks a ton perreal. I wasted entire day for this. at the end, so simple.
You need to at least quote your expansions better. "${NEWARRAY[@]}"
@perreal: also $an, $item.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.