Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

linux

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?

like image 844
valpa Avatar asked Aug 26 '13 05:08

valpa


People also ask

How do I concatenate two columns in Unix?

paste is the command that can be used for column-wise concatenation. The paste command can be used with the following syntax: $ paste file1 file2 file3 …

How do I display a specific column in Unix?

1) The cut command is used to display selected parts of file content in UNIX. 2) The default delimiter in cut command is "tab", you can change the delimiter with the option "-d" in the cut command. 3) The cut command in Linux allows you to select the part of the content by bytes, by character, and by field or column.


2 Answers

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

like image 183
ДМИТРИЙ МАЛИКОВ Avatar answered Oct 19 '22 05:10

ДМИТРИЙ МАЛИКОВ


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
like image 25
devnull Avatar answered Oct 19 '22 05:10

devnull