How to align 3 files based on the value of the first column

I have 3 text files c.dat, n.datand the h.dat contents seem in this format

c.dat    n.dat    h.dat
1 0.ccc  3 1.nnn  1 2.hhh
2 0.ccc  4 1.nnn  2 2.hhh
4 0.ccc  5 1.nnn  5 2.hhh

Required Conclusion:

1 0.ccc Inf 2.hhh
2 0.ccc Inf 2.hhh
3 Inf 1.nnn Inf
4 0.ccc 1.nnn Inf
5 Inf 1.nnn 2.hhh
6 Inf Inf Inf
7 ....

Each file has ~ 100 lines, but they do not always start with 1 and are not always sequential.

I need to align 3 files on the first column, so if other files do not have it, it is populated with something like NA or NaN or Inf ....

Thank!

+5
source share
4 answers
awk '
{
        if(FNR==1){f++}
        a[$1,f] = $2
        if($1 > max){max = $1}
}

END{
        for(j=1;j<=max;j++){
          printf("%d\t", j)
          for(i=1;i<=f;i++){
            if(!a[j,i]){printf("Inf\t")}
            else{printf("%s\t", a[j,i])}
          }
          printf("\n")
        }
}' ./c.dat ./n.dat ./h.dat

Output

$ ./awk.dat
1       0.ccc   Inf     2.hhh
2       0.ccc   Inf     2.hhh
3       Inf     1.nnn   Inf
4       0.ccc   1.nnn   Inf
5       Inf     1.nnn   2.hhh
+4
source

- perl script 1 100, 3 grep -, awk, , Inf.

.

0

Clean Bash.

maxindex=0

while read idx val ; do                         # build array from c.dat
    c[idx]=$val
    [ $maxindex -lt $idx  ] && maxindex=$idx
done < 'c.dat'

while read idx val ; do                         # build array from n.dat
    n[idx]=$val
    [ $maxindex -lt $idx  ] && maxindex=$idx
done < 'n.dat'

while read idx val ; do                         # build array from h.dat
    h[idx]=$val
    [ $maxindex -lt $idx  ] && maxindex=$idx
done < 'h.dat'

for (( idx=1; idx<=$maxindex; idx+=1 )); do
    echo -e "$idx  ${c[idx]:-INF} ${n[idx]:-INF} ${h[idx]:-INF}"
done
0
source

man paste should give you an answer - paste -d ' ' file1 file2 file3

-1
source

All Articles