valpa
valpa

Reputation: 367

how to combine two variable column-by-column in bash

I have two variables, multi-line.

VAR1="1
2
3
4"

VAR2="ao
ad
af
ae"

I want to get

VAR3="1ao
2ad
3af
4ae"

I know I can do it by:

echo "$VAR1" > /tmp/order
echo "$VAR2" | paste /tmp/order  -

But is there any way to do without a temp file?

Upvotes: 14

Views: 17319

Answers (2)

devnull
devnull

Reputation: 123608

You can say:

$ VAR3=$(paste <(echo "$VAR1") <(echo "$VAR2"))
$ echo "$VAR3"
1   ao
2   ad
3   af
4   ae

It's not clear whether you want spaces in the resulting array or not. Your example that works would contain spaces as in the above case.

If you don't want spaces, i.e. 1ao instead of 1 ao, then you can say:

$ VAR3=$(paste <(echo "$VAR1") <(echo "$VAR2") -d '')
$ echo "$VAR3"
1ao
2ad
3af
4ae

Upvotes: 5

paste <(echo "$VAR1") <(echo "$VAR2") --delimiters ''

Upvotes: 30

Related Questions