Assigning the names from overlapping regions

I have 2 files; file 1 having smaller positions that overlap with the positions with positions in file2.
file1

aaa 20 22 apple
aaa 18 25 banana
aaa 12 30 grapes
aaa 22 25 melon

file2

aaa 18 26 cdded
aaa 10 35 abcde

I want to get something like this
output

aaa 18 26 cdded banana melon  
aaa 10 35 abcde apple  banana grapes melon

Why apple is not in the output?

aaa 18 26 cdded apple banana melon  
aaa 10 35 abcde apple  banana grapes melon

I see apple falls under the range 20 to 22 in file1 and this range is in between 18 to 26!

1 Like

I am really sorry thats my mistake

OK, here is an awk approach that might work:

awk '
        NR == FNR {
                A[$NF] = $0
                next
        }
        {
                for ( k in A )
                {
                        split ( A[k], V )
                        if ( $2 >= V[2] && $3 <= V[3] )
                        {
                                T[k] = T[k] ? T[k] OFS $NF : A[k] OFS $NF
                        }

                }
        }
        END {
                for ( k in T )
                        print T[k]
        }
' file2 file1

Try

awk     'NR == FNR      {MIN[$4]=$2; MAX[$4]=$3; next}
                        {for (i in MIN)
                           if (MIN >= $2 && MAX <= $3) $0=$0" "i}
         1
        ' file1 file2
aaa 18 26 cdded apple melon banana
aaa 10 35 abcde grapes apple melon banana