Search code examples
bashconcatenation

Concatenating multiple line variables using newline


I have two variables var1 and var2 that could either be multiple lines or could be completely empty. For example, either one could look like:

line/1
line/2

or


I want to concatenate them so that when put together var1 outputs as is, and var 2 outputs as is right below the last line of var1. There are 4 cases, either var1 is empty and var2 is not, var 2 is empty and var 1 is not, both are empty, or neither are empty. I dont want any whitespace or an empty line if one of the variables is empty. So if var 1 is empty I do not want,


line/1

or vice versa.

Other than using a if, elif, else block, is there a way I could do this or do I HAVE to use an if else block.

In addition, for the last case where neither are empty how can I concatenate these two? I have tried

var3="${var1}\n${var2}" 

but that doesn't seem to work. Any tips would be much appreciated.


Solution

  • Using bash, you can use this function for this job:

    concat() {
       printf '%s' "${1:+$1$'\n'}" "${2:+$2$'\n'}";
    }
    

    Use of "${1:+$1$'\n'}" appends \n to $1 only if $1 is null/unset.

    As per man bash:

    ${parameter:+word} Use Alternate Value. If parameter is null or unset, nothing is substituted, otherwise the expansion of word is substituted.

    Examples:

    concat 'line1' 'line2'
    

    line1
    line2
    

    concat 'line1' ''
    

    line1
    

    concat '' 'line2'
    

    line2
    

    concat '' ''
    

    concat 'line1
    line2
    line3' ''
    

    line1
    line2
    line3