Adjust gap between 2 columns to make them look straight

awkline-editorsedsolaristext formatting

file1.txt:

hi
wonderful
amazing
sorry
superman
superhumanwith
loss

file2.txt :

1
2
3
4
5
6
7

When i try to combine using paste -d" " file1.txt file2.txt > actualout.txt

actualout.txt :

hi 1
wonderful 2
amazing 3
sorry 4
superman 5
superhumanwith 6
loss 7

But i want my output to look like this
desired

OUT.txt :

hi             1
wonderful      2
amazing        3 
sorry          4
superman       5 
superhumanwith 6
loss           7

Which command can be used to combine 2 files an look like the desired output?
Solaris 5.10
ksh
nawk, sed, paste

Best Answer

awk 'FNR==1{f+=1;w++;}
     f==1{if(length>w) w=length; next;}
     f==2{printf("%-"w"s",$0); getline<f2; print;}
    ' f2=file2 file1 file1

Note: file1 is quite intentionally read twice; the first time is to find the maximum line length, and the second time is to format each line for the final concatenation with corresponding lines from file2. — file2 is read programatically; its name is provided by awk's variable-as-an-arg feature.

Output:

hi             1
wonderful      2
amazing        3
sorry          4
superman       5
superhumanwith 6
loss           7

To handle any number of input files, the following works.but *Note: it does not cope with repeating the same filename. ie each filename arg refers to a different file. It can, however, handle files of different lengths - beyond a files EOF, spaces are used.

awk 'BEGIN{ for(i=1; i<ARGC; i++) { 
              while( (getline<ARGV[i])>0) { 
                 nl[i]++; if(length>w[i]) w[i]=length; }
              w[i]++; close(ARGV[i])
              if(nl[i]>nr) nr=nl[i]; }
            for(r=1; r<=nr; r++) {
              for(f=1; f<ARGC; f++) {
                if(r<=nl[f]) getline<ARGV[f]; else $0=""  
                printf("%-"w[f]"s",$0); } 
              print "" } }
    ' file1 file2 file3 file4

Here is the output with 4 input files:

hi             1 cat   A 
wonderful      2 hat   B 
amazing        3 mat   C 
sorry          4 moose D 
superman       5       E 
superhumanwith 6       F 
loss           7       G 
                       H 
Related Question