Q:

Appending matching strings to specific lines (sed/bash)

Using bash/sed, I am trying to search for matching string and when a match is found it appends that variable to the end of the applicable line.
Two lists:
[linuxbox tmp]$ cat lista
a 23
c 4
e 55
b 2
f 44
d 74
[linuxbox tmp]$ cat listb
a 3
e 34
c 84
b 1
f 500
d 666666

#!/bin/bash
rm -rf listc

cat listb |while read rec
do
    var1="$(echo $rec | awk '{ print $1 }')"
    var2="$(echo $rec | awk '{ print $2 }')"
    if egrep "^$var1" lista; then
            sed "/^$var1/ s/$/ $var2/1" lista >> listc
    fi
done

when I run it I get:
[linuxbox tmp]$ ./blah.sh
a 23
e 55
c 4
b 2
f 44
d 74

[linuxbox tmp]$ cat listc
a 23 3
c 4
e 55
b 2
f 44
d 74
a 23
c 4
e 55 34
b 2
f 44
d 74
a 23
c 4 84
e 55
b 2
f 44
d 74
a 23
c 4
e 55
b 2  1
f 44
d 74
a 23
c 4
e 55
b 2
f 44 500
d 74
a 23
c 4
e 55
b 2
f 44
d 74 666666

The output i'm trying to get to is:
a 23 3
e 55 34
c 4 84
b 2  1
f 44 500
d 74 666666

What am I doing wrong here? Is there a better way to accomplish this?
Thank you in advance.

A:

If you don't mind getting a sorted output:
join <(sort lista) <(sort listb)

