14

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?

2 Answers 2

30

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

Sign up to request clarification or add additional context in comments.

5 Comments

what's the <() operator called?
@KurtisNusbaum "<()" is called a "process substitution". Not all shells support it, but most popular ones do: google.com/search?q=process+substitution
This is not working for me in Linux (Ubuntu 18.04.1 LTS). The paste line gives the following error: script.sh: 11: script.sh: Syntax error: "(" unexpected.
On OSX, I had to do paste --d '' <(echo "$VAR1") <(echo "$VAR2"). Using either the --delimiters arg, or putting it at the end of the command gave me errors about No such file or directory.
I was having the same problem as @iamyojimbo on macOS and using --d gave me paste: illegal option -- - usage: paste [-s] [-d delimiters] file ... . Using -d resolved it
5

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

Comments

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.