【发布时间】:2013-04-10 21:28:07
【问题描述】:
我有一个 perl 脚本,它打开一个 txt 文件,对其进行解析,以便将适当的文本输出到 csv 文件。我现在为一个文件工作得很好,但是我有很多类似的文件要以完全相同的方式处理。我希望能够自动执行此操作,因此代码将通过 file1.txt 工作并解析我想要 output.csv 的文本,然后通过 file2.txt 工作并将此输出附加到相同的 output.csv。我在下面包含了我的代码的相关位,仅排除了在 while 循环中进行实际解析的代码,因为我不需要更改它。输入文件的名称一致,例如file1.txt、file2.txt、file3.txt 等都在同一个目录中
my $mode = "none";
open(my $infile,"<","file1.txt") or die $!;
open (my $outfile,">>","output.csv") or die $!;
while (<$infile>)
{
chomp;
if ($_ =~ /^Section 1/) {
$mode = "sec1";
}
if ($_ =~ /^Section 2/) {
$mode = "sec2";
}
if ($mode =~ "sec1") {
$_=~ tr/,//d;
if ($_ =~ /.\%$/){
print $outfile $_;
print $outfile "\n";
}
else{
print $outfile $_;
}
}
}
close $infile;
close $outfile;
输出文件应该类似于这个(显然不是这个文本,我只是强调它必须附加输出,我想我已经使用 >> 而不是 >)
this is from file 1
this is from file 2
this is from file 3
【问题讨论】: