How to concatenate 2 multiline strings line by line, like 'paste' does with two files

吃可爱长大的小学妹 提交于 2019-12-24 10:46:47

问题


I'm searching for a way to concatenate two multiline strings line by line, like paste does with file contents. Is there a equivalent tool like paste for multiline strings? REMARKS: I don't want to use files in any manner!

String content 1:

A1 
A2
A3
A4

String content 2:

B5
B6
B7

I would like to have:

A1 B5
A2 B6
A3 B7
A4

Maybe with results like a full outer join, having an empty column entry on every position where no data is given? That would be interesting, too: e.g.

A1 B5 C8
A2 B6 C9
A3 B7 C10
A4    C11

As an example:

> string3=$(combine "$string1" "$string2")
> echo "$string3"
> A1 B5
  A2 B6
  A3 B7
  A4

Thanks for tips and hints ;)


回答1:


You can use paste for this, without making use of files!

$ paste -d' ' <(echo "$string1") <(echo "$string2")
A1 B5
A2 B6
A3 B7
A4 



回答2:


'paste' can do the concatenation with more than two files.

cat file1

A1 
A2
A3
A4

cat file2

B5
B6
B7

cat file3

C8
C9
C10
C11

Can you please try

paste file1 file2 file3 > output

For me, I got this

A1  B5  C8
A2  B6  C9
A3  B7  C10
A4      C11

Is this what you want?




回答3:


The simplest way in bash would be to convert the strings to arrays and then simply write the data out in tab separated format based upon the longest string. Here is a quick example:

#!/bin/bash

outfile="${1:-colcomb.txt}"
:> $outfile

s1='A1 
A2
A3
A4'

s2='B5
B6
B7'

## read into arrays
ar1=( $s1 )
ar2=( $s2 )

## use largest array to drive output
if test "${#ar1[@]}" -ge "${#ar2[@]}" ; then
    for ((i=0; i<${#ar1[@]}; i++)); do
        echo -n "${ar1[$i]}" >> $outfile
        test -n "${ar2[$i]}" && echo -e "\t${ar2[$i]}" >> $outfile
    done
    echo "" >> $outfile  # append newline to file (optional)
else
    for ((i=0; i<${#ar2[@]}; i++)); do
        test -n "${ar1[$i]}" && echo -n "${ar1[$i]}" >> $outfile
        echo -e "\t${ar2[$i]}" >> $outfile
    done
    echo "" >> $outfile  # append newline to file (optional)
fi

exit 0

output:

$ bash ap2col.sh

$ cat colcomb.txt
A1      B5
A2      B6
A3      B7
A4

That way you could add a third or fourth string if required.



来源:https://stackoverflow.com/questions/24798817/how-to-concatenate-2-multiline-strings-line-by-line-like-paste-does-with-two

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!