【问题标题】:Splitting a `.bed` file based on chromosomes into `chromosomeName.bed` with perl使用perl将基于染色体的`.bed`文件拆分为`chromosomeName.bed`
【发布时间】:2016-02-05 07:42:26
【问题描述】:

我正在尝试使用perl 根据染色体将.bed 文件拆分为多个文件。比如我的输入文件是example.bed:

chr1    12190   12227
chr1    12595   12721
chr2    876522  876688
chr2    887378  887521
...

而我的理想输出是两个.bed 文件:

chr1.bed

chr1    12190   12227
chr1    12595   12721

chr2.bed

chr2    876522  876688
chr2    887378  887521

我知道使用awk 执行此操作更容易,但我希望弄清楚如何使用perl 脚本执行此操作。

【问题讨论】:

    标签: perl file split


    【解决方案1】:

    您可以维护文件句柄的哈希:

    $ 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
    

    如果您有数百种不同的染色体,您可能会用完打开的文件句柄。在这种情况下,您必须为每一行打开追加、打印和关闭。

    【讨论】:

    • 而且,是的,awk 是等效的,但更简单:awk '{f = $1 ".bed"; print > f}' example.bed
    【解决方案2】:

    可能有点冗长,但如果您需要操作(排序、搜索等)内容,将提供灵活性。通常,如果数据文件适合内存,我更喜欢将整个文件放入内存并从那里开始。

    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  887521
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-07-14
      • 1970-01-01
      • 2013-03-12
      • 2018-09-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多