mygrep -- 搜索文件夹内所有文件的字符串匹配(perl)

 

mygrep:搜索字符串在某个文件dir内,包括内部所有的子文件夹,Win和*nix通用 

 

 1#!/usr/bin/perl
 2
 3 use strict;
 4 use File::Spec::Functions;
 5
 6 my %usage={};
 7 $usage{"name"}="mygrep";
 8 $usage{"version"}="0.1";
 9 $usage{"author"}="xxx002";
10 $usage{"mail"}='thomasliu83@gmail.com';
11 $usage{"cmd"}=" Usage: mygrep pattern-string directory ";
12
13 my $g_pattern="";
14 my $g_dir="";
15
16 #search pattern string in file
17 sub search_file
18 {
19         my ($filepath)=@_;
20         open(my $hFile,"<$filepath") || return 1;
21         my @content=();
22         while(<$hFile>)
23         {
24                 push @content,$_ if m/$g_pattern/o;
25         }
26         close($hFile);
27         print "*** In File $filepath /n", @content if @content;
28 }
29
30 #search files in DIR
31 sub search_dir
32 {
33         my ($dirpath)=@_;
34         die "Error: $dirpath not exsit/n" if !$dirpath;
35         print "Starting search in $dirpath  ... /n";
36         my @list_dirs=();
37         if (-d $dirpath)
38         {
39                 push @list_dirs,$dirpath;
40         }
41         while($dirpath=pop(@list_dirs))
42         {
43                 opendir(my $hDir, $dirpath) || (print "Can not open $dirpath" && next);
44                 for my $file_index (readdir($hDir))
45                 {
46                         my $tmp=catfile($dirpath,$file_index);
47                         if (-d $tmp && ($file_index ne '.' && $file_index ne '..'))
48                         {
49                                 push(@list_dirs,$tmp);
50                                 next;
51                         }
52                         if ( -T $tmp)
53                         {
54                                 search_file($tmp);
55                         }
56                 }
57         }
58 }
59
60 sub usage{
61         print $usage{"name"}."/n Ver".$usage{"version"};
62         print " Write by ".$usage{"author"}." <".$usage{"mail"}.">/n";
63         print $usage{"cmd"}."/n";
64 }
65
66 #main----------------
67 #
68 sub main{
69
70         ($g_pattern,$g_dir)=@ARGV;
71         usage() and die "Error: Parameter error/n" if !$g_pattern || !$g_dir;
72
73         search_dir($g_dir);
74 }
75
76 main();

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值