使用Windows PERL搜索模式

时间:2015-01-11 04:56:12

标签: perl

我的目的是搜索特定单词或完整语句,并将这些单词粘贴到另一个文本文件中。例如,您可以获取日志文件,我需要查找特定日期时间的异常,并将其粘贴到另一个文本文件示例result.txt中。以下是以下脚本。请帮助我这方面

chomp(@ARGV)

if(@ARGV!=2) {
    print "Please Pass two parameters";
    print "Usage: $ <File_name><pattern\n>";
}

$File_name     = $ARGV[0];
$res_File_name = $Filename . "\.res";
$Pattern       = $ARGV[1];

open(FD,"<File_name>")      or die("File $File_name could not be opened ");
open(WFD,"<res_File_name>") or die("File $res_File_name could not be opened ");

while(<FD>) {
    print WFD $-if(/$Pattern);
}

close(FD);
close(WFD);

这是一个日志文本文件

log.txt

2015-1-11 11:21:00 [Exception or Error] System.IO exception. I need to find those exceptions and paste that in result.txt. Not that only  i have a document say i have some paragraph ex: Hello World, i need to find that hello world and paste that in text file. 

为此,我在这里传递了两个参数if (@ARGV != 2),我需要打印一条消息。

其次我需要传递这两个参数

ARGV[0]ARGV[1] File_nameres_file_name,我从原始文件中获取标量值并将其传递到下一个res文件。

O / p:2015-01-10 or any other argument you pass that will be displayed

1 个答案:

答案 0 :(得分:0)

@hari_cheerful:您可以尝试以下perl代码:

use strict;
use warnings;

chomp(@ARGV);

if(@ARGV!=2)
{
    print "Please Pass two parameters\n". "Usage: <Filename><pattern>\n";
    exit;
}

my $Filename     = $ARGV[0];
my ($file,$ext) = $Filename =~ /(.*)(\..*?)/;
my $res_File_name = "$file" . "\.res";
my $Pattern       = $ARGV[1];

open(my $ip,'<', $Filename)      or die("File $Filename could not be opened ");
open(my $op,'>', $res_File_name) or die("File $res_File_name could not be opened ");

while(<$ip>) {
    if($_ =~ /$Pattern/is)
      {
         print $op $Pattern . "\n";
        }
     elsif($_ =~ /\d{4}\-\d{1,2}\-\d{1,2}\s*\d{2}:\d{2}:\d{2}\s*\[Exception\s*.*?/is)
      {
         print $op $_ . "\n";
        }   

}
close($ip);
close($op);