Bash paste command output formatting

Ramesh picture Ramesh · Oct 20, 2014 · Viewed 28.7k times · Source

File1:

1
2

File2:

1 2 3
4 5

File3:

x x x
yy yy
zz

paste file1 file2 file2 gives me a tab separated output:

1       1 2 3   x x x
2       4 5     yy yy
                zz

paste -d" " file1 file2 file3 gives me the output:

1 1 2 3 x x x
2 4 5 yy yy
  zz

I want it like below:

1 1 2 3 x x x
2 4 5   yy yy
        zz

Any idea if this is possible or should I try any other command?

Answer

user3442743 picture user3442743 · Oct 20, 2014

Could use sed after to remove tabs

 paste file file2 file3 | sed 's/\t/ /'

 1 1 2 3 x x x
 2 4 5   yy yy
         zz

Here is a general purpose awk script that will work on any number of file with any formatting.

awk '
    {x=ARGIND;a[x]=a[x]>(b=length($0))?a[x]:b}
    {F[FNR,x]=$0}
    END{
            for(q=1;q<=FNR;q++)
            {
                    for(i=1;i<=ARGC;i++)
                    {
                    printf( "%-"a[i]"s ",F[q,i])
                    }print ""
            }
    }' file{1,2,3,4)