1

I have two arrays of same lengths like following:

arr1[1]=2
arr1[2]=5

arr2[1]=x
arr2[2]=y

I am trying to create a string like "2 x 5 y".

Since the length of the arrays can be a variable, is there any way to do this without using a loop and string concatenation (like parameter expansion or something) ?

2
  • 1
    You can use loops even when the array lengths are varying Commented Dec 29, 2014 at 6:04
  • That's what I meant. I can use loops. But I want to know if there are any other tricks like expansion to avoid loops. Sorry for the misunderstanding. Commented Dec 29, 2014 at 6:07

1 Answer 1

1

You can use paste with process substitution:

arr1[1]=2
arr1[2]=5

arr2[1]=x
arr2[2]=y

s=$(paste <(printf "%s\n" "${arr1[@]}") <(printf "%s\n" "${arr2[@]}") |
    tr '[[:space:]]' ' ')
echo "$s"
2 x 5 y
Sign up to request clarification or add additional context in comments.

2 Comments

Perfect! Thanks. One quick question, with tr, are you removing extra space? Because it seems to work even without the tr.
Yes I am just removing extra whitespaces (space/tab/newlines) etc with tr. You can skip it also.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.