将自定义标头添加到目录中的特定文件

时间:2016-06-28 17:03:25

标签: linux perl

我想添加一个唯一的一行标题,该标题与指定目录中的每个文件FOCUS * .tsv文件有关。之后,我想将所有这些文件合并到一个文件中。

首先我尝试了sed命令。

`my $cmd9 = `sed -i '1i$SampleID[4]' $tsv_file`;` print $cmd9;

看起来它有效但在我将所有这些文件合并到代码的下一部分中的一个文件后,插入的行被列为每个文件四次。

我已经尝试了以下Perl脚本来完成相同的操作,但它删除了文件的内容,只打印出添加的标题。

我正在寻找最简单的方法来完成我正在寻找的东西。 这是我尝试过的。

#!perl
use strict;
use warnings;
use Tie::File;

my $home="/data/";                                                     
my $tsv_directory = $home."test_all_runs/".$ARGV[0];
my $tsvfiles = $home."test_all_runs/".$ARGV[0]."/tsv_files.txt";

my @run_directory = (); @run_directory = split /\//, $tsv_directory; print "The run directory is #############".$run_directory[3]."\n";

my $cmd = `ls $tsv_directory/FOCUS*\.tsv > $tsvfiles`; #print "$cmd";
my $cmda = "ls $tsv_directory/FOCUS*\.tsv > $tsvfiles"; #print "$cmda";

my @tsvfiles =();
#this code opens the vcf_files.txt file and passes each line into an array for indidivudal manipulation
open(TXT2, "$tsvfiles");
        while (<TXT2>){  
                push (@tsvfiles, $_);   
                }
close(TXT2);

foreach (@tsvfiles){
        chop($_);
}

#this loop works fine
for my $tsv_file (@tsvfiles){

      open my $in, '>', $tsv_file or die "Can't write new file: $!";    
      open my $out, '>', "$tsv_file.new" or die "Can't write new file: $!";  

    $tsv_file =~ m|([^/]+)-oncomine.tsv$| or die "Can't extract Sample ID";
    my $sample_id = $1;
    #print "The sample ID is ############## $sample_id\n";
    my $headerline = $run_directory[3]."/".$sample_id;
    print $out $headerline;
    while( <$in> ) {
    print $out $_;
    }

    close $out;
    close $in;

unlink($tsv_file);
rename("$tsv_file.new", $tsv_file);

}

谢谢

1 个答案:

答案 0 :(得分:1)

显然,打开读取的文件时出现错误的'>'是问题所在并且已经解决了。

但是,我想就其余部分代码发表一些意见。

  • 通过将外部ls重定向到文件,然后将此文件读入数组来构建文件列表。然而,这正是glob的工作,所有这些都被

    取代
    my @tsvfiles = glob "$tsv_directory/FOCUS*.tsv";
    

    然后你也不需要chomp,并且使用的chop实际上会受到伤害,因为它删除了最后一个字符,而不仅仅是换行符(或者真的$/)。

  • 使用chop可能不是您想要的。如果要删除换行符($/),请使用chomp

  • 要提取匹配并分配匹配,常见的习惯用语是

    my ($sample_id) = $tsv_file =~ m|([^/]+)-oncomine.tsv$| 
        or die "Can't extract Sample ID: $!";
    

    请注意,我还添加了$!,以实际打印错误。否则我们就不知道它是什么。

  • unlinkrename似乎覆盖了另一个文件。您可以使用核心模块File::Copy

    中的move来执行此操作
    use File::Copy qw(move);
    move ($tsv_file_new, $tsv_file)  
        or die "Can't move $tsv_file to $tsv_file_new: $!";
    

    _new重命名为$tsv_file,因此会覆盖它。

至于如何组合文件,需要更精确的解释。

相关问题