【问题标题】:How to concatenate 2 multiline strings line by line, like 'paste' does with two files如何逐行连接 2 个多行字符串,就像 'paste' 对两个文件所做的那样
【发布时间】:2014-09-08 01:06:15
【问题描述】:

我正在寻找一种方法来逐行连接两个多行字符串,就像 paste 对文件内容所做的那样。对于多行字符串,是否有类似 paste 的等效工具?评论: 我不想以任何方式使用文件!

字符串内容1:

A1 
A2
A3
A4

字符串内容2:

B5
B6
B7

我想要:

A1 B5
A2 B6
A3 B7
A4

也许像完全外连接这样的结果,在没有给出数据的每个位置都有一个空列条目?这也很有趣:例如

A1 B5 C8
A2 B6 C9
A3 B7 C10
A4    C11

举个例子:

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

感谢您的提示和提示;)

【问题讨论】:

    标签: bash concatenation multiline


    【解决方案1】:

    'paste' 可以连接两个以上的文件。

    猫文件1

    A1 
    A2
    A3
    A4
    

    猫文件2

    B5
    B6
    B7
    

    猫文件3

    C8
    C9
    C10
    C11
    

    你可以试试

    paste file1 file2 file3 > output
    

    对我来说,我得到了这个

    A1  B5  C8
    A2  B6  C9
    A3  B7  C10
    A4      C11
    

    这是你想要的吗?

    【讨论】:

    • 这是我想要的,但更确切地说,我不想使用paste 来连接文件列,因为我已经知道这个功能。我正在寻找一种比使用文件并连接它们更优雅的方式。
    【解决方案2】:

    bash 中最简单的方法是将字符串转换为数组,然后根据最长的字符串以制表符分隔的格式简单地写出数据。这是一个简单的例子:

    #!/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
    

    输出:

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

    如果需要,您可以添加第三个或第四个字符串。

    【讨论】:

    • 现在在 posix shell 中;-)
    【解决方案3】:

    您可以为此使用paste,而无需使用文件!

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

    【讨论】:

    • 好的,那我接近那个解决方案了:),但是错过了回声并将分隔符更改为-d' '
    猜你喜欢
    • 2016-10-13
    • 2018-12-27
    • 2017-07-22
    • 2015-12-24
    • 1970-01-01
    • 1970-01-01
    • 2017-05-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多