Bring two files together

Dear Forum,

I was wondering if anybody could help me to bring to files together.

I have two text files. In the text file each record occupies two lines. First the ID number and in the next line text.

$ cat text.txt
+12345678
text_A
+12345644
text_B
+12334241
text_C
+1234586
text_D
+12231241
text_E
+1234
text_F

The second file also contains the ID and a header. Each record is a line.

$ cat head.txt
12345678	Head_A
12345644	Head_B
12334241	Head_C
1234	Head_F

I would need to combine the two files according to the exact ID number.

$ cat outfile.txt
+12345678 Head_A
text_A
+12345644 Head_B
text_B
+12334241 Head_C
text_C
+1234	Head_F
text_F

I could reformat the text.txt file into one line per record and use the ID to grep and combine the hits. I guess not very elegant and slow. I was also thinking of use a grep inside a while loop but I guess this would be slow too.

I was hoping to find an array solution but I would need some help:

awk 'FNR==NR{a[$1];next}{ for(i=1;i<=NF;i++){ if($i ~ "+" && $i in a) {print $i} else print $i} }' head.txt text.txt

I would appreciate some help. Thanks!

awk '
        NR == FNR {
                i = substr($0,2);
                getline;
                A = $0
                next
        }
        $1 in A {
                print "+" $0 RS A[$1]
        }
' text.txt head.txt
awk 'FNR==NR {h["+" $1]=$2;next} {print $0, h[$1]}' head.txt text.txt 

The requestor seemed to want to eliminate the records not in the head file. So try a small adaption to Aia's code:

awk 'FNR==NR {h["+" $1]=$2;next} $1 in h {print $0, h[$1]; getline; print}' head text
+12345678 Head_A
text_A
+12345644 Head_B
text_B
+12334241 Head_C
text_C
+1234 Head_F
text_F

Based on the title of the post and on the following opening sentence:

I took it as the opposite, even when I did not see any output for text_D or text_E

Nevertheless, for that case I would suggest:

awk 'FNR==NR {h[$1]=$2;next} $1 in h {print "+" $1, h[$1];print $2}' head.file RS="+" text.file

Dear Yoda, dear Aia, dear RudiC,

thank you all for helping me to find three perfect solutions for my problem. @Aia, sorry if my description of the problem was not so clear.

Here the three solutions that worked for me:

time awk 'FNR==NR {h["+" $1]=$2;next} $1 in h {print $0, h[$1]; getline; print}' text.txt header.txt > outA.tmp

real	0m20.552s
user	0m17.823s
sys	0m2.697s
time awk '
        NR == FNR {
                i = substr($0,2);
                getline;
                A = $0
                next
        }
        $1 in A {
                print "+" $0 RS A[$1]
        }
' text.txt head.txt > outB.tmp

real	0m22.600s
user	0m19.482s
sys	0m3.078s
time awk 'FNR==NR {h[$1]=$2;next} $1 in h {print "+" $1, h[$1];print $2}' header.txt RS="+" text.txt > outC.tmp

real	1m29.579s
user	1m25.451s
sys	0m3.584s