-
Notifications
You must be signed in to change notification settings - Fork 1
/
bgrep.go
68 lines (57 loc) · 1.18 KB
/
bgrep.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
package main
import (
"bytes"
"encoding/hex"
"flag"
"fmt"
"io/ioutil"
"os"
"path/filepath"
)
func errorf(msg string, args ...interface{}) {
fmt.Fprintf(os.Stderr, msg, args...)
}
var searchBin []byte
func searchFile(path string) {
fileData, err := ioutil.ReadFile(path)
if err != nil {
errorf("Failed to open %s: %v\n", path, err)
} else if i := bytes.Index(fileData, searchBin); i != -1 {
fmt.Printf("%s: found at byte %d\n", path, i)
} else if showAll {
fmt.Printf("%s: not found\n", path)
}
}
func walker(path string, info os.FileInfo, err error) error {
if info.IsDir() {
return nil
}
searchFile(path)
return nil
}
var showAll bool
func main() {
all := flag.Bool("a", false, "show all results")
recurse := flag.Bool("r", false, "recursive search")
flag.Parse()
showAll = *all
if flag.NArg() < 2 {
return
}
var err error
searchBin, err = hex.DecodeString(flag.Arg(0))
if err != nil {
errorf("Failed to parse search string: %v\n", err)
os.Exit(1)
}
for _, fileName := range flag.Args()[1:] {
if *recurse {
err = filepath.Walk(fileName, walker)
if err != nil {
errorf("Walk failed: %v\n", err)
}
} else {
searchFile(fileName)
}
}
}