1 package main
 2 
 3 import (
 4     "fmt"
 5     "io/ioutil"
 6     "os"
 7     "path/filepath"
 8     "strings"
 9 )
10 
11 var matchCount = 0
12 var ch = make(chan int, 512)
13 
14 func findFile(path string, text string) {
15     var pathArray [100]string
16     var count = 0
17     filepath.Walk(path, func(path string, info os.FileInfo, err error) error {
18         if err != nil {
19         }
20         //find text
21         if !info.IsDir() {
22             if info.Size() < 1024*1024 {
23                 pathArray[count] = path
24                 count++
25                 if count >= 100 {
26                     count = 0
27                     go findText(pathArray[0:100], text)
28                     <-ch
29                 }
30             }
31         }
32         return nil
33     })
34     go findText(pathArray[0:count], text)
35     <-ch
36 
37     fmt.Printf("一共发现了 %d 个匹配的文件", matchCount)
38 
39 }
40 
41 func findText(paths []string, text string) {
42     for _, path := range paths {
43         fi, err := os.Open(path)
44         if err != nil {
45             panic(err)
46         }
47         defer fi.Close()
48         fd, err := ioutil.ReadAll(fi)
49         if err != nil {
50             panic(err)
51         }
52 
53         if strings.Index(string(fd), text) > -1 {
54             matchCount++
55             fmt.Println(path)
56         }
57     }
58     ch <- 1
59 }
60 
61 func main() {
62     args := os.Args
63     if len(args) < 3 {
64         fmt.Println("需要两个参数 path text")
65         return
66     }
67     path := args[1]
68     text := args[2]
69 
70     _, err := os.Stat(path)
71 
72     if err != nil {
73         fmt.Println("path不存在")
74     } else {
75         findFile(path, text)
76     }
77 }

 计数器增加的时候应该加锁