[Solved] sum up third and second columns by 0 difference

Hi Friends,

I have the following file

chr1 1 2 
chr1 2 3
chr1 3 4
chr1 4 5
chr1 5 6
chr1 19 20
chr1 20 21
chr1 21 22

I want to compare the third column of record 1 to second column of next record and if the difference is zero, consider its third column and match it to next record and so on. Finally, my output would be

chr1 1 6
chr1 19 22

Thanks in advance.

Try this..

awk '{if(! s){a=$1FS$2;s=$3}else{if (($2-s) > 0){k=s;p=$2;s=$3}else {s=$3}}}END{print a,k"\n"$1,p,s}' file
1 Like

Thanks for your time pamu. A small change.

I would like to match the chr (first column) column before calculating the difference.

For ex, for the same above input

chr1 1 2 
chr1 2 3
chr1 3 4
chr1 4 5
chr2 5 6
chr1 19 20
chr1 20 21
chr1 21 22

should yield me

chr1 1 5
chr2 5 6
chr1 19 22

awk -f t.awk b

where t.awk:

BEGIN {
 a_min=9999999;
 a_max=-1;
 lr="";
}
{
 if (lr != $1 && length(lr)>0) {
  print lr " " a_min " " a_max;
  a_min=9999999;
  a_max=-1;
 }
 if ($2 < a_min) a_min=$2;
 if ($3 > a_max) a_max=$3;
 lr=$1;
}
END {
  print lr " " a_min " " a_max;
}
1 Like

Perfect! Thanks to both of you.