我试图使用perl将一个.bed文件分割成多个基于染色体的文件。例如,我的输入文件是example.bed
chr1 12190 12227
chr1 12595 12721
chr2 876522 876688
chr2 887378 887521
...我的理想输出是两个.bed文件:
chr1.bed 1.床
chr1 12190 12227
chr1 12595 12721chr2.床
chr2 876522 876688
chr2 887378 887521我知道使用awk来做这件事更容易,但我希望找到如何使用perl脚本来做到这一点。
发布于 2015-11-04 17:39:06
您可以维护文件句柄的散列:
$ cat example.bed
chr1 12190 12227
chr1 12595 12721
chr2 876522 876688
chr2 887378 887521
$ perl -ane '
open $out{$F[0]}, ">", $F[0].".bed" unless $out{$F[0]};
print { $out{$F[0]} } $_;
' example.bed
$ cat chr1.bed
chr1 12190 12227
chr1 12595 12721
$ cat chr2.bed
chr2 876522 876688
chr2 887378 887521如果你有数百个不同的染色体,你可能会耗尽打开的文件句柄。在这种情况下,您必须为每一行打开追加、打印和关闭。
发布于 2015-11-04 19:56:20
也许有点冗长,但如果您需要对内容进行操作(排序、搜索等),则会允许灵活性。一般来说,如果数据文件适合内存,我更愿意将整个文件填充到内存中,然后从那里开始。
use strict;
use warnings;
# initialize the hash to contain the content
my %bed;
# read the entire file into memory
# stuffing same into a hash
while(<DATA>)
{
chomp;
my @line = split;
my $car = $line[0];
my $cdr = join(' ', @line[1,-1]);
push(@{$bed{$car}}, $cdr);
}
foreach my $k (keys %bed)
{
# create filename
my $fn = $k . '.txt';
# open file for writing
open OUT, '>', $fn or die "Cannot open $fn, $!";
# print each element of the hash key
foreach my $e (@{$bed{$k}}) { print OUT "$e\n"; }
# close file`
close OUT;
}
exit(0);
__DATA__
chr1 12190 12227
chr1 12595 12721
chr2 876522 876688
chr2 887378 887521https://stackoverflow.com/questions/33528184
复制相似问题