-1

Here I have tried awk script to compare fields from two different files.

awk 'NR == FNR {if (NF >= 4) a[$1] b[$4]; next} {for (i in a) for (j in b)  if (i >= $2 && i <=$3 && j>=$2 && j<=$3 ) {print $1, $2, $3, i, j; next}}' file1 file2

Input files:

File1:

24926   17  206 25189   5.23674 5.71882 4.04165 14.99721    c     
50760   17  48  50874   3.49903 4.25043 7.66602 15.41548    c     
104318  15  269 104643  2.94218 5.18301 5.97225 14.09744    c     
126088  17  70  126224  3.12993 5.32649 6.14936 14.60578    c     
174113  16  136 174305  4.32339 2.36452 8.60971 15.29762    c     
196474  14  89  196626  2.24367 5.16966 7.33723 14.75056    c  
......
......

File2:

GT_004279   1   280
GT_003663   19891   20217
GT_003416   22299   23004
GT_003151   24916   25391
GT_001715   39470   39714
GT_001585   40896   41380
....
....

The output which I got is:

GT_004279 1 280 2465483 2639576
GT_003663 19891 20217 2005645 2005798
GT_003416 22299 23004 2291204 2269898
GT_003151 24916 25391 2501183 25189
GT_001715 39470 39714 3964440 3950417
......
......

The desired output should be 1st and 4th field values from file1 lies in between 2nd and 3rd field values from file2. For example, If I have taken above given lines as INPUT files, the output must be..

GT_003151   24916   25391   24926   25189

If I guess correctly the problem is within the If loop. So, Could someone help to rectify this problem.

Thanks

2
  • 1
    First of all, why don't you show us an example of the lines from the table you expect to have outputted for the shown input, since you can't expect someone to figure out what you intend by looking at broken code if even the computer can't figure it out.
    – clearlight
    Mar 24, 2015 at 6:08
  • 1
    I did not know you could assign variable this way: {if (NF >= 4) a[$1] b[$4]; next} I would have used {if (NF >= 4) {a[$1] ;b[$4]}; next}. Since both work this is not your problem.
    – Jotne
    Mar 24, 2015 at 6:19

1 Answer 1

2

You need to make composite keys and iterate through them. When you create such composite keys they are separated by SUBSEP variable. So you just split based on that and do the check.

awk '
NR==FNR{ flds[$1,$4]; next }
{
  for (key in flds) {
    split (key, fld, SUBSEP)
    if ($2<=fld[1] && $3>=fld[2])
      print $0, fld[1], fld[2]
  }
}' file1 file2
GT_003151   24916   25391 24926 25189
2
  • 2
    +1. FYI With GNU awk 4 for 2d arrays you can write {flds[$1][$4]}...{for (i in flds) for (j in flds[i])} and avoid the split().
    – Ed Morton
    Mar 24, 2015 at 12:51
  • 1
    Thanks @EdMorton. You know me, I've always been bashful (pun intended) of gawk v4. :). Mar 24, 2015 at 13:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.