Joining

I do have many files of the following format.

File_1.txt

1 24
2 25
3 27
4 28
5 29
6 1

File_2.txt

2 5
3 8
4 9
5 10

File_3.txt

3 7
4 8
5 9

I wanted to merge all these files based on the first column like this:

1 24 0 0
2 25 5 0
3 27 8 7
4 28 9 8
5 29 10 9
6 1 0 0

Basically merge it based on the first column and add 0's at the missing positions.
I tried:

awk  '{i=$1;sub(i,x);A=A$0} FILENAME==ARGV[ARGC-1]{print i A}' File_1.txt File_2.txt File_3.txt

But the missing values are ignored and no 0's were added.

Let me know the best way to do this using awk.

You could use join command:

join -a 1 -a 2 -e '0' -o 1.1 1.2 2.2 file1 file2 > tmp
join -a 1 -a 2 -e '0' -o 1.1 1.2 1.3 2.2 tmp file3

---------- Post updated at 12:28 ---------- Previous update was at 12:16 ----------

Here is an approach using awk based on some assumptions:

awk '
        BEGIN {
                F = "file1"
                while ( (getline line < F) > 0 )
                {
                        split (line, A)
                        F1[++c] = A[2]
                }
                close (F)
                F = "file2"
                while ( (getline line < F) > 0 )
                {
                        split (line, A)
                        F2[A[1]] = A[2]
                }
                close (F)
                F = "file3"
                while ( (getline line < F) > 0 )
                {
                        split (line, A)
                        F3[A[1]] = A[2]
                }
                close (F)
        }
        END {
                for ( k = 1; k <= c; k++ )
                        print k, F1[k], F2[k]?F2[k]:"0", F3[k]?F3[k]:"0"
        }
' /dev/null

Thanks, but it won't help. I have many files to join

awk '

F != FILENAME { FILENO++ ; F=FILENAME }
{ A[$1,FILENO]=$2 }
!($1 in C) { C[$1]++; COL[++L]=$1 }

END {
        for(N=1; N<=L; N++)
        {
                printf("%d", COL[N]+0);
                for(FILE=1; FILE<=FILENO; F++)
                        printf(" %d", A[COL[N],FILE]+0);
                printf("\n");
        }
}' file1 file2 file3 ...