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