mygrep — 搜尋資料夾內所有檔案的字串匹配(perl)

來源:互聯網
上載者:User
 

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

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.