在文件中查找文本的Perl脚本

Windows里没有grep工具,不方便对文件的内容进行查找,随手写了一个Perl脚本,脚本写得不是很简洁,但能工作。





Github: https://gist.github.com/2273079

 
 
   
   
#!/usr/bin/perl -w
############################################################################
# File: findtext.pl
# Brief: Match text content in a directory
#
# Usage: findtext.pl DIR PATTERN
# - DIR work directory
# - PATTERN pattern for text search
#
# Author: Thinkhy
# Date: 2011-11-8
# Changes:
#
############################################################################


use strict ;
use Encode ;
use File:: Glob ':glob' ;



my $cnt = @ARGV ;
if ( $cnt <= 0 )
{
     print " Usage: findtext.pl DIR PATTERN
- DIR work directory
- PATTERN pattern for text search
" ;
     exit - 1 ;
}


my $dir = decode ( "gb2312" , $ARGV [ 0 ]);
my $pattern0 = $ARGV [ 1 ];
my $pattern = decode ( "gb2312" , $ARGV [ 1 ]);
print $pattern ;



chomp ( $dir );
chomp ( $pattern );


$dir =~ s/\\/\//g ;




print "Search content in directory: " . $dir . "\n" ;
print "===================================================\n" ;
print "\n" ;


Find ( $dir );


my $deep = 0 ;
sub Find
{
     my $path = shift ;


     $deep ++ ;


     my @pathes = listpath ( $path );
     my @files = listfile ( $path );




#print join "\n", @pathes;
# print join "\n", @files;
     foreach ( @files )
     {
         my $file = $_ ;
         #print "Search".$file."\n";
         if ( isPatternOnFile ( $file , $pattern ))
         {
             print $file . "\n"
         }
     }


     if ( $pathes [ 0 ])
     {
         foreach ( @pathes )
         {
             Find ( $_ );
         }
     }


     $deep -- ;
}




sub listpath
{
     my $path = shift ;
     my @list = bsd_glob "$path/*" ;
     #my @list = <$path/*>;
     my @pathes = grep { - d } @list ;
     return @pathes ;
}




sub listfile
{
     my $path = shift ;
     my @list = bsd_glob "$path/*" ;
     #my @list = <$path/*.*>;
     my @files = grep { - f } @list ;
     return @files ;
}


sub isPatternOnFile
{
     my ( $file , $pattern ) = @_ ;
     my $temp ;


     #read the entire file
     open my $fh , "<:encoding(UTF-8)" , $file or die $! ;
     {
         local $/ ;
         $temp = <$fh> ;
     }
     return 1 if ( $temp =~ /$pattern/i ) or return 0 ;
}



                
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值