脚本扫描脚本所在的文件夹并搜索特定文件[Perl]

时间:2017-03-27 22:18:05

标签: perl file search directory

我正在创建一个脚本,我在特定文件夹中打开,包含两种不同类型的文件。 '安全' (secure.text,secure.001.text等)文件和' message' (message.txt等)文件。每个文件都包含年,日,日,小时和分钟的日志。我希望能够扫描这些文件并创建一个包含2006年1月所有日志条目的新文件。此脚本的目的是只能扫描一组数据(安全),而不是所有数据(消息)。

我的脚本找到当前工作目录时遇到问题。据我了解,perl将使用脚本的位置作为当前目录。我正在使用opendir和closedir函数,并且提示脚本目录中有60个文件,但是当我删除一些文件只是为了测试它时,它仍然说60,这让我相信这不是使用当前目录。尽管正确的正则表达式,它也没有找到' secure'

我得到的输出是"发现文件'安全'。"

#!/usr/bin/perl


use strict;
use warnings;



#Locate and scan all of the files 

 #list all files in same dir as this perl script.
 my $dirname = "."; 
 opendir( my $dh, $dirname ) #sets $dh as the current working directory
    or die "Can't open dir '$dirname':$!\n"; #Kills if can not open current directory.
 my @all_the_file; #Instantiates new variable that accounts for all of the files in the current dir.
 while( my $file = readdir($dh) ) { #$file accounts for every file on device. 
    push( @all_the_file, $file ); #Pushes files in current directory to $file.

 }
 closedir( $dh ); 

 #Gets all of the secure files. 

 my @all_the_secure_file;
 @all_the_secure_file = grep(/^secure(\.\d{1,2})?$/, @all_the_file);

 #Itterate over secure files. 

my $filename = "secure";
open( my $fhin, "<", $filename)
    or die "Can't open '$filename':$!\n";
chomp( my @lines = <$fhin> ) ;
close($fhin);

 #Match the Regex of Jan. 

 my @jan_lines = grep( /^Jan/ , @lines ) ;
print "The file '$filename' = " . @lines . " lines.\n";
print "Size of \@jan_lines = " . @jan_lines . "\n";

 #Print and create new file with Data. 

 my $filename2 = "secure.1";
open( my $fhin, "<", $filename)
    or die "Can't open '$filename':$!\n";
chomp( my @lines2 = <$fhin> ) ;
close($fhin);

my @jan_lines2 = grep( /^Jan/ , @lines2 ) ;
print "The file '$filename2' = " . @lines2 . " lines.\n";
print "Size of \@jan_lines2 = " . @jan_lines2 . "\n";

 exit;

1 个答案:

答案 0 :(得分:1)

你真的应该使用一些模块。以下示例使用Path::Tiny

use 5.014;
use warnings;
use Path::Tiny;

my $root = path("/some/path");
my $iter = $root->iterator({recurse => 1});

while(my $path = $iter->()) {
    next unless $path->basename =~ /(secure|message)\.(\d+)?\.txt/i;

    my $type = $1;
    #my $num = $2; #???

    my @lines = grep { /^Jan/ } $path->lines();
    say "in the $path is ", scalar @lines, " lines for Jan";

    my $new = path( ($type =~ /secure/i) ? "/some/where/secure.txt" : "/some/nosecure/message.txt" );
    $new->spew(@lines);
}

未经测试,但它应该+ - 与您的脚本相同,甚至更多,因为它会逐步搜索......