2014-09-13 61 views
1

我想解析日志文件并将它们转换为.csv文件。我在分割功能方面遇到问题。例如,我在日志文件中有以下内容:21a94551,00:00:59.643; ERROR;。当我尝试分割逗号(,)和分号(;)时,输出csv文件中的时间戳将丢失.643。我想保持完整的时间(00:00:59.643)。我在日志文件中有多行(全部使用不同的数字),所以这些值不是显式的。使用Text :: CSV_XS分割函数

当我使用拆分后打印功能函数值被输出到屏幕上确定,但在CSV文件

我是新来的Perl。有人能解释我做错了什么吗?我认为这个问题可能与字符串的处理方式有关。

use strict; 
use Cwd; 
use Excel::Writer::XLSX; 
use Text::CSV_XS; 
use Spreadsheet::Read; 

my $dirname = getcwd;    # Set the directory to current working directory. 
opendir (DIR, $dirname) || die;  # Open the current directory 
my @FileNameList = readdir(DIR); # Load the names of files in to an array 

foreach (@FileNameList)    #Read each of the file names 
{ 
    my $FileName = $_; 
    my $Output; 

    if ($FileName =~ m/iusp_\d+.log/) 
     { 
     print ("\n". $FileName." \n Correct Log File Found"); 

open (my $file, "<", $FileName); 

while (<$file>) { 
     chomp; # Remove the \n from the last field 
     my $Line = $_; # Create the variable SLine and place the contents of the current line there 

     if ($Line =~ m/ERROR/) # Select any line that has "ERROR" inside it. 
     { 
      my @fields = split /[,;]/, $Line; # Split up the line $Line by ", ;" 
      my $csv = Text::CSV_XS->new();   # Create new CSV 
      $csv->combine(@fields); 
      my $csvLine = $csv->string(); 
      print $csvLine, "\n"; 
      { 
       $Output = $csvLine . "\n"; 
      } 
      my $OutputFileName = $FileName . ".csv"; 
      print("\n Saving File:" . $OutputFileName); 
      open(MyOutputFile, ">>$OutputFileName"); 
      print MyOutputFile $Output; 
     } #End of IF Statement 
    } #End of while statement 

回答

6

简化你的正则表达式。您不需要.*perldoc -f split)。该点由split作为分隔符处理,因为它位于字符类方括号内。

use warnings; 
use strict; 
use Data::Dumper; 

my $Line = '21a94551,00:00:59.643;ERROR;'; 
my @fs = split /[,;]/, $Line; 
print Dumper(\@fs); 

__END__ 
$VAR1 = [ 
      '21a94551', 
      '00:00:59.643', 
      'ERROR' 
     ]; 
+0

谢谢你,我想,和它的作品在屏幕上,但没有得到的结果相同.csv文件。 – 2014-09-14 11:07:25

+0

不客气。我建议如下。 1.接受提供的答案之一,因为他们解决您的原始问题。 2.发布一个新问题,但在此之前...... 3.删除与您的问题无关的所有代码(请阅读http://sscce.org和http://perlmonks.org/?node_id=745674) – toolic 2014-09-14 12:30:35

2

[]里面有什么不是正则表达式,它是一组字符或字符范围或类。你告诉它拆就,.*;当你只是想拆就,;split /[,;]/, ...