-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
63 lines (60 loc) · 1.61 KB
/
main.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
package main
import (
"bufio"
"flag"
"fmt"
"os"
"strings"
)
func main() {
var searchStr, fileName, dirName, line, output string
var result []string
var err error
var isCaseInSensitivity = flag.Bool("i", false, "Ignore case when searching")
var isWordMatch = flag.Bool("w", false, "Word match when searching")
var outputFile = flag.String("o", "", "File to write the matches")
var recursive = flag.Bool("r", false, "recursive search from directory")
flag.Parse()
if len(os.Args) < 2 {
fmt.Println("Usage: grep [option(s)...] pattern [file_name]")
return
}
nonFlagValues := flag.Args()
searchStr = nonFlagValues[0]
if len(nonFlagValues) == 1 {
if *recursive {
dirName, err = os.Getwd()
if err != nil {
fmt.Println(err)
}
result, _ = recursiveCallFromDir(dirName, searchStr, *isCaseInSensitivity, *isWordMatch, *recursive)
} else {
scanner := bufio.NewScanner(os.Stdin)
for scanner.Scan() {
line = scanner.Text()
output = searchString(searchStr, line, *isCaseInSensitivity, *isWordMatch)
if output != "" {
fmt.Println(output + "\n")
}
}
}
if *outputFile != "" {
writeFile(result, *outputFile)
}
} else {
if *recursive {
dirName = nonFlagValues[1]
if err != nil {
fmt.Println(err)
}
result, _ = recursiveCallFromDir(dirName, searchStr, *isCaseInSensitivity, *isWordMatch, *recursive)
} else {
fileName = nonFlagValues[1]
result, err = readFileLineByLine(fileName, searchStr, *isCaseInSensitivity, *isWordMatch, *recursive)
finalResult(strings.Join(result, "\n"), err)
}
if *outputFile != "" {
writeFile(result, *outputFile)
}
}
}