使用 Windows PERL 搜索模式

Search Pattern Using Windows 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

@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);