How to achieve side by side output in Bash?


A portable tool for this is paste:

(
    echo A
    echo a
    echo B
    echo b
    echo C
    echo c
    echo D
    echo d
) | paste - -

From the specification:

The default operation of paste shall concatenate the corresponding lines of the input files. The <newline> of every line except the line from the last input file shall be replaced with a <tab>.

[…]

If - is specified for one or more of the files, the standard input shall be used; the standard input shall be read one line at a time, circularly, for each instance of -.

Lines of varying length may generate output that is not perfectly aligned. To see an example, run:

(
    echo A line longer than others
    echo a
    echo B
    echo b
) | paste - -

You can fix this by piping to column:

(
    echo A line longer than others
    echo a
    echo B
    echo b
) | paste - - | column -t -s $'\t'

Note $'\t' generates a tab character in some shells, portably you can do it with "$(printf '\t')"; column itself is not portable though.



Source link

Leave a Comment