如何删除许多文件中的标题行并使用Perl对它们进行重命名

问题描述:

我需要帮助来处理许多小文件。如果它存在,我需要删除第一行(标题日期行),然后重命名文件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 

这里有一个办法做到这一点:

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

低的内存父子解决方案:

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; 
}; 

这是未经测试!