我需要帮助尝试处理许多小文件。我需要删除第一行(标题日期行)(如果存在),然后重命名文件q_dat_20110816.out
=> q_dat_20110816.dat
。
我想出了如何打开文件并进行匹配并打印出我需要删除的行。
现在我需要弄清楚如何删除该行,然后完全重命名该文件。
你会怎么做?
测试代码:
#!/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
答案 0 :(得分: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;
}
答案 1 :(得分: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;
};
未经测试!