Intelligently merge two files

I have two files as the following:

file1:

243
242
243
242
242

file2:

243          car       360    396k
242          bike       240    217k

I want the corresponding $3 in file 2 added as $2 in file 2.

The expected output would be:

243 360
242 240
243 360
242 240
242 240

I figured that I can do this through two loops, but I am not sure how to extract the exact values that I would need, here is that I was thinking of:

 while read y; do
                while read z; do

                done<file1
        done<file2

Is there a better way to do this using only awk or sed?

Thanks.

---------- Post updated at 11:31 AM ---------- Previous update was at 11:18 AM ----------

I think I figured out a bash based method. I can find matches now. Figuring out a way to print should be straight forward.

while read y; do
                while read z; do
                        a=$(echo $y | awk '{print $1}')
                        if [ "$a" = "$z" ]; then
                                echo $y
                        else
                                echo nomatch
                        fi
                done<file1
        done<file2

Hello Jamie_123,

You could try following also, which may help you in same.

 awk 'FNR==NR{X[$1]=$3;next} ($1 in X){print $1 OFS X[$1]}' file2 file1
 

Output will be as follows.

243 360
242 240
243 360
242 240
242 240
 

Thanks,
R. Singh

1 Like
awk 'NR == FNR {a[$1] = $3; next} {print $1, (a[$1] == "" ? "nomatch" : a[$1])}' file2 file1
1 Like