2011-08-19 79 views
2

我需要幫助來處理許多小文件。如果它存在,我需要刪除第一行(標題日期行),然後重命名文件q_dat_20110816.out =>q_dat_20110816.dat如何刪除許多文件中的標題行並使用Perl對它們進行重命名

我想出瞭如何打開文件並進行匹配並打印出需要刪除的行。

現在我需要弄清楚如何刪除該行,然後完全重命名該文件。

你會如何處理這個問題?

測試代碼:

#!/usr/local/bin/perl 
use strict; 
use warnings; 

my $file = '/share/dev/dumps/q_dat_20110816.out'; 
$file = $ARGV[0] if (defined $ARGV[0]); 

open DATA, "< $file" or die "Could not open '$file'\n"; 
while (my $line = <DATA>) { 
     $count++; 
     chomp($line); 
     if ($line =~m/(Data for Process Q)/) { 
       print "GOT THE DATE: --$line\n"; 
       exit; 
     } 
} 
close DATA; 

示例文件:q_dat_20110816.out

Data for Process Q, for 08/16/2011 
Make Model Text 
a  b  c 
d  e  f 
g  h  i 

新文件:q_dat_20110816.dat

Make Model Text 
a  b  c 
d  e  f 
g  h  i 

回答

1

這裏有一個辦法做到這一點:

use strict; 
use warnings; 

my @old_file_names = @ARGV; 

for my $f (@old_file_names){ 
    # Slurp up the lines. 
    local @ARGV = ($f); 
    my @lines = <>; 

    # Drop the line you don't want. 
    shift @lines if $lines[0] =~ /^Data for Process Q/; 

    # Delete old file. 
    unlink $f; 

    # Write the new file. 
    $f =~ s/\.out$/.dat/; 
    open(my $h, '>', $f) or die "$f: $!"; 
    print $h @lines; 
} 
+0

謝謝。很好地工作。 – jdamae

1

低的內存父子解決方案:

use strict; 
use warnings; 

for my $fni (@ARGV) { 
    open(FI, '<', $fni) or die "cant open in '$fni', $!,"; 
    my $fno = $fni; $fno =~ s/\.out$/.dat/; 
    open(FO, '>', $fno) or die "cant open out '$fno', $!,"; 
    foreach (<FI>) { 
     print FO unless $. == 1 and /^Data for Process Q/; 
    }; 
    close FO; 
    close FI; 
    unlink $fni; 
}; 

這是未經測試!

相關問題