简体   繁体   中英

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
paste -d' ' <(echo "$NUMS") <(echo "$TITLES")

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.

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]}"
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM