Roselover
Roselover

Reputation: 93

How to use paste command for different lengths of columns

I have:

file1.txt       file2.txt      file3.txt
   8               2               2
   1               2               1
   8               1               0
                   3               3
                   5               3
                   3
                   4               

I want to paste all these three columns in ofile.txt

I tried with

paste file1.txt file2.txt file3.txt > ofile.txt

Result I got in ofile.txt:

ofile.txt:
   8               2               2
   1               2               1
   8               1               0
          3               3
          5               3
          3
          4       

Which should come

ofile.txt
   8   2   2
   1   2   1
   8   1   0
       3   3
       5   3
       3
       4      

Upvotes: 1

Views: 1801

Answers (2)

anubhava
anubhava

Reputation: 784998

You can try this paste command in bash using process substitution:

paste <(sed 's/^[[:blank:]]*//' file1.txt) file2.txt file3.txt
8       2       2
1       2       1
8       8       0
        3       3
        5       3
        3
        4

sed command is used to remove leading whitespace from file1.txt.

Upvotes: 1

Walter A
Walter A

Reputation: 19982

I can reproduce your output when I make inputfiles with tabs.
paste also uses tabs betwen the columns and does this how he thinks it should. You see the results when I replace the tabs with -:

    # more x* | tr '\t' '-'
    ::::::::::::::
    x1
    ::::::::::::::
    -1a
    -1b
    -1c
    -1d
    ::::::::::::::
    x2
    ::::::::::::::
    -2a
    -2b
    ::::::::::::::
    x3
    ::::::::::::::
    -3a
    -3b
    -3c
    -3d
    -3e
    -3f
    -3g
   # paste x? | tr '\t' '-'
    -1a--2a--3a
    -1b--2b--3b
    -1c---3c
    -1d---3d
    ---3e
    ---3f
    ---3g

Think how you want it. When you want correct indents, you need to append lines with tab for files with less lines. Or manipulate the result: 3 tabs into 4 and 4 tabs at the beginning of the line to 5 tabs.

sed -e 's/\t\t\t/\t\t\t\t/' -e 's/^\t\t\t\t/\t\t\t\t\t/'

Upvotes: 1

Related Questions