Stack Exchange Network

Stack Exchange network consists of 175 Q&A communities including Stack Overflow, the largest, most trusted online community for developers to learn, share their knowledge, and build their careers.

Visit Stack Exchange
    Post Made Community Wiki by don_crissti
1
source | link

Here's how to do it with join and preserve line order, headers, footers etc...

join -1 2 -2 1 -a 1 -e 0 -o 1.1,1.2,1.3,1.4,1.5,2.2,2.3,2.4 \
<(sort -k2,2 <(nl -ba -nrz file1)) <(sort -k1,1 file2) | \
sort -k1,1n | cut -d\  -f2-

result:

TABLES REF-IO HEAD-IO DIFF-IO REF-SELECT HEAD-SELECT DIFF-SELECT
test 200 500 -300 5 7 -2
exam 2 3 -1 0 7 -7
final 2 1 1 12 6 6
mail 4 2 2 0 0 0
TOTAL 208 506 -298 20 23 -3

How it works:

nl -ba -nrz file1 numbers the lines in file1, the output is then sorted on 2nd field; file2 is also sorted on 1st field and the results are then joined on 2nd field from 1st input and 1st field from 2nd input, replacing missing input fields with 0:

000003 exam 2 3 -1 0 7 -7
000004 final 2 1 1 12 6 6
000005 mail 4 2 2 0 0 0
000001 TABLES REF-IO HEAD-IO DIFF-IO REF-SELECT HEAD-SELECT DIFF-SELECT
000002 test 200 500 -300 5 7 -2
000006 TOTAL 208 506 -298 20 23 -3

this is then sorted on 1st field with sort -k1,1n to restore line order and then cut -d\ -f2- removes the line numbers. You could further prettify it with column e.g. .... | column -t:

TABLES  REF-IO  HEAD-IO  DIFF-IO  REF-SELECT  HEAD-SELECT  DIFF-SELECT
test    200     500      -300     5           7            -2
exam    2       3        -1       0           7            -7
final   2       1        1        12          6            6
mail    4       2        2        0           0            0
TOTAL   208     506      -298     20          23           -3