Carson McManus
Carson McManus

Reputation: 344

How do I concatenate each line of 2 variables in bash?

I have 2 variables, NUMS and TITLES.

NUMS contains the string

1
2
3

TITLES contains the string

A
B
C

How do I get output that looks like:

1 A
2 B
3 C

Upvotes: 1

Views: 953

Answers (4)

Ivan
Ivan

Reputation: 7317

Convert them to arrays, like this:

NUMS=($NUMS)
TITLES=($TITLES)

Then loop over indexes of whatever array, lets say NUMS like this:

for i in ${!NUMS[*]}; {
    # and echo desired output
    echo "${NUMS[$i]} ${TITLES[$i]}"
}

Upvotes: 1

Raman Sailopal
Raman Sailopal

Reputation: 12917

Awk alternative:

awk 'FNR==NR { map[FNR]=$0;next } { print map[FNR]" "$0} ' <(echo "$NUMS") <(echo "$TITLE")

For the first file/variable (NR==FNR), set up an array called map with the file number record as the index and the line as the value. Then for the second file, print the entry in the array as well as the line separated by a space.

Upvotes: 0

tripleee
tripleee

Reputation: 189908

Having multi-line strings in variables suggests that you are probably doing something wrong. But you can try

paste -d ' ' <(echo "$nums") - <<<"$titles"

The basic syntax of paste is to read two or more file names; you can use a command substitution to replace a file anywhere, and you can use a here string or other redirection to receive one of the "files" on standard input (where the file name is then conventionally replaced with the pseudo-file -).

The default column separator from paste is a tab; you can replace it with a space or some other character with the -d option.

You should avoid upper case for your private variables; see also Correct Bash and shell script variable capitalization

Bash variables can contain even very long strings, but this is often clumsy and inefficient compared to reading straight from a file or pipeline.

Upvotes: 2

Carson McManus
Carson McManus

Reputation: 344

paste -d' ' <(echo "$NUMS") <(echo "$TITLES")

Upvotes: 3

Related Questions