EDIT - After OP's input file and comments.
First we will swap the start and end position, if start position is greater than end position and then we will sort this file.
Say this perl script is strand.pl -
use strict;
use warnings;
open my $file, '<',$ARGV[0] or die "Unable to open input file: $!";
my @data;
while (<$file>) {
@data = split;
if ($data[1] > $data[2]) {
my $temp = $data[1];
$data[1] = $data[2];
$data[2] = $temp;
}
print join("\t",@data),"\n";
}
Use -
perl strand.pl input.file | sort -k1,1n -k2,2n > sorted.file
Now we will merge the overlapping positions.
Then use this perl script say merge.pl -
use strict;
use warnings;
open my $file, '<',$ARGV[0] or die "Unable to open input file: $!";
my @data;
while (<$file>) {
if (not @data) {
@data = split;
next;
}
my @new = split;
if ($new[0] == $data[0] and $new[1] <= $data[2] + 1) {
if ($data[2] < $new[2]){
$data[2] = $new[2];
}
}
else {
print join("\t", @data), "\n";
@data = @new;
}
print join("\t", @data), "\n" if eof $file;
}
Use -
perl merge.pl sorted.file > result.file
My textfile does not contain any header line. I am using it to illustrate my question. Sorry about the confusion.
Benm's solution from http://www.biostars.org/post/show/7825/how-to-get-non-overlapping-coordinates-from-a-list-that-contains-overlapping-coordinates/ works perfectly on your dataset. Did you try it?
I tried but it should not report/output sub-region within the region. It means that, we still get region 5-10 even if it covered under region 4-12. According to his solution, it should take that into account but it does not seem so. I might be missing some tricks.
Could you give an example (editing your question for instance) of what output you get with Benm's solution? I get exactly the solution you describe in your question...
Benm's solution works for some coordinates but then on some parts it does not work. Here is the input file http://pastie.org/4221091 Here is the output file http://pastie.org/4221095
I think I understood. I edited my code and added
if ($data[2] < $new[2]). I think now it should work on your sorted file and will not report so called underlaps. Please have a look.Vikas, your solution works for some coordinates just as Benm's solution. Please see my input and output file in the previous reply. Thanks again.
There are 2 problems in your input file because of which you are not getting desired results with my code. One is that the file is not sorted and for that I have already mentioned to use sort command on first 2 columns. Second is that you have negative strands also. Do you want to treat them separately or you want to merge them also.
Eg- If you have
You want to merge them or want to keep them separately?
I want to merge them.
Please see my edit and let me know if it works.
It works pretty well. Thank you.