Print Files Side-by-Side – How to Print Two Files in Two Columns Side-by-Side

command linepastetext formatting

I want to print two files in two columns — first file on the left side and second on the right side.

paste doesn't do the job, because it can only insert a character as delimiter, so if first file lines have different length output will be twisted:

$ cat file1
looooooooong line
line
$ cat file2
hello
world
$ paste file1 file2
looooooooong line   hello
line    world

If it was a command to add trailing spaces like fmt --add-spaces --width 50 the problem would be solved:

$ paste <(fmt --add-spaces --width 50 file1) file2
looooooooong line                                 hello
line                                              world

But I don't know a simple way to do this.

So how to merge and print several files horizontally without twisting? Actually, I just want to look at them simultaneously.


UPD: command to add trailing spaces does exist (for example, xargs -d '\n' printf '%-50s\n')

But solution like

$ paste <(add-trailing-spaces file1) file2

does not work as expected when file1 has fewer lines than file2.

Best Answer

What about paste file{1,2}| column -s $'\t' -tn?

looooooooong line line  hello
line                    world
  • This is telling column to use Tab as columns' separator where we takes it from the paste command which is the default seperator there if not specified; generally:

    paste -d'X' file{1,2}| column -s $'X' -tn

    where X means any single character. You need to choose the one which granted that won't be occur in your files.

  • The -t option is used to determine the number of columns the input contains.

  • This will not add long tab between two files while other answers does.
  • this will work even if there was empty line(s) in file1 and it will not print second file in print area of file1, see below input/ouput

    Input file1:

    looooooooong line
    
    line
    

    Input file2:

    hello
    world
    

    Output:

    looooooooong line  hello
                       world
    line
    
Related Question