Mygrep: search strings in a file Dir, including all internal subfolders, win and * nix universal
1#! /Usr/bin/perl
2
3Use strict;
4UseFile: SPEC: functions;
5
6My % 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
13My $ G_pattern="";
14My $ G_dir="";
15
16# Search pattern string in file
17Sub Search_file
18{
19My($ Filepath) =@_;
20Open(My $ Hfile,"<$ Filepath") |Return 1;
21My @ Content= ();
22While(<$ Hfile>)
23{
24Push @ Content,$ _ If M/$ G_pattern/O;
25}
26Close($ Hfile);
27Print "* ** In file$ Filepath /N",@ Content If @ Content;
28}
29
30# Search files in Dir
31Sub Search_dir
32{
33My($ Dirpath) =@_;
34Die "Error:$ DirpathNot exsit/N" If!$ Dirpath;
35Print "Starting search in$ Dirpath.../N";
36My @ List_dirs= ();
37If(-D $ Dirpath)
38{
39Push @ List_dirs,$ Dirpath;
40}
41While($ Dirpath=Pop(@ List_dirs))
42{
43Opendir(My $ Hdir,$ Dirpath) | (Print "Can not open$ Dirpath"&&Next);
44For My $ File_index(Readdir($ Hdir))
45{
46My $ TMP= Catfile ($ Dirpath,$ File_index);
47If(-D $ TMP&&($ File_index Ne '.'&&$ File_index Ne '..'))
48{
49Push(@ List_dirs,$ TMP);
50Next;
51}
52If(-T $ TMP)
53{
54Search_file ($ TMP);
55}
56}
57}
58}
59
60Sub Usage{
61Print $ Usage{"Name"}."/NVer".$ Usage{"Version"};
62Print "Write".$ Usage{"Author"}."<".$ Usage{"Mail"}.">/N";
63Print $ Usage{"CMD"}."/N";
64}
65
66# Main ----------------
67#
68Sub Main{
69
70($ G_pattern,$ G_dir) =@ Argv;
71Usage ()And Die "Error: parameter error/N" If!$ G_pattern|!$ G_dir;
72
73Search_dir ($ G_dir);
74}
75
76Main ();