无法使用perl在文件中搜索字符串

时间:2014-01-30 23:09:28

标签: perl shell

我有一个小的shell脚本,我正在搜索文件中的一些字符串,而在perl中执行相同操作时,我无法获得逻辑。请帮帮我。

for i in `ls *.txt`
do

    if [[ `cat $i|grep "Records"` && `cat $i|grep "HTTP/Responce authorized"`  && `cat $i|grep "responseData class"` ]]
    then
        echo "Pass" >> temp 
    else
        echo "Fail" >> temp
    fi

done

这是我到目前为止所做的:

#!/usr/bin/perl

use strict;
use warnings;

my $file = 'TC_01.txt';
my $value1 = 'totalRecords';
my $value2 = 'responseData';
#my $value3 = '200';

open my $info, $file or die "Could not open $file: $!";

while( my $line = <$info>) {
    #print $line;
    #last if $. == 2;
    if (($line =~ /$value1/) && ($line =~ /$value2/)) {
        print "Pass","\n";
        last;
    }
    else {
        print "Fail";
        last;
    }
}
close $info;

2 个答案:

答案 0 :(得分:1)

只要您能够将字符串[123]替换为您实际查找的文本,就可以使用以下内容。

my @fileList;

opendir(DIR,"/path/to/dir") || die "error opening directory";
while(readdir(DIR)) {
        if($_ =~ /.*\.txt$/) {push(@fileList,$_)}
}
closedir(DIR);

foreach my $txtFile (@fileList) {

        my ($a,$b,$c) = (0,0,0);
        open(FILE,"<$txtFile");
        while(<FILE>) {
                if($_ =~ /string1/) { $a=1 }
                if($_ =~ /string2/) { $b=1 }
                if($_ =~ /string3/) { $c=1 }
        }
        close(FILE);

        open(OUTFILE,">>temp");
        if($a && $b && $c) {
                print OUTFILE "Pass\n"
        }
        else {
                print OUTFILE "Fail\n"
        }
        close(OUTFILE);

}

答案 1 :(得分:1)

可以找到my $content = do { local $/; <$fh> };部分的说明here

#!/usr/bin/perl

use strict;
use warnings;

# File to write to
open my $temp, ">>", "temp" or die $!;

for my $file (sort glob "*.txt") {
    my $fh;
    open $fh, $file or die $!;
    my $content = do {
        local $/;
        <$fh>;
    };

    if ($content =~ /Records/
            and $content =~ /HTTP\/Responce authorized/
            and $content =~ /responseData class/) {
        print $temp "Pass\n";
    }
    else {
        print $temp "Fail\n";
    }
}