Skip to content

Instantly share code, notes, and snippets.

@taoliu
Last active October 25, 2024 14:13
Show Gist options
  • Select an option

  • Save taoliu/a44244f98ae2ac0d37282f15167cf69a to your computer and use it in GitHub Desktop.

Select an option

Save taoliu/a44244f98ae2ac0d37282f15167cf69a to your computer and use it in GitHub Desktop.
Convert samtools depth output to bedGraph
#!/usr/bin/env perl
# A script to convert samtools (>v1.3) depth (with -aa option) output
# to bedGraph by merging continous positions with the same value.
if ( $#ARGV < 0 ) {
print "Need 1 parameter! $0 <samtools depth output (with -aa)>\n";
exit ();
}
$f = $ARGV[ 0 ];
open( IN,$f);
$_ = <IN>;
chomp;
( $chr,$s,$v ) = split;
$e = $s;
$s -= 1;
while( <IN> ){
chomp;
( $c_chr,$c_s,$c_v ) = split;
if( $c_chr eq $chr && $c_v != $v ) {
print join( "\t",( $chr, $s, $e, $v ) ),"\n";
$s = $c_s - 1;
$v = $c_v;
$e = $c_s }
elsif( $c_chr eq $chr && $c_v == $v ) {
$e = $c_s;
}
elsif( $c_chr ne $chr ) {
print join( "\t",( $chr,$s,$e,$v ) ),"\n";
$chr = $c_chr;
$s = $c_s-1;
$v = $c_v;
$e = $c_s;
}
}
# last region
print join( "\t",( $chr,$s,$e,$v ) ),"\n";
@taoliu
Copy link
Copy Markdown
Author

taoliu commented Oct 25, 2024

Thanks! Updated.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment