-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
89 lines (76 loc) · 1.63 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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
package main
import (
"bufio"
"fmt"
"os"
"strings"
)
func findPhraseInFile(filePath string, phrase string, newFilePath string) error {
file, err := os.Open(filePath)
if err != nil {
return err
}
defer func() {
if err := file.Close(); err != nil {
fmt.Printf("Error occurred while closing the file: %+v\n", err)
}
}()
newFile, err := os.Create(newFilePath)
if err != nil {
return err
}
defer func() {
if err := newFile.Close(); err != nil {
fmt.Printf("Error occurred while closing the new file: %+v\n", err)
}
}()
writer := bufio.NewWriter(newFile)
scanner := bufio.NewScanner(file)
block := ""
for scanner.Scan() {
line := scanner.Text()
if len(line) == 0 { // empty line
if strings.Contains(block, phrase) {
_, err := writer.WriteString(block + "\n")
if err != nil {
return err
}
err = writer.Flush()
if err != nil {
return err
}
}
block = ""
} else {
block += line + "\n"
}
}
// check last block
if strings.Contains(block, phrase) {
_, err := writer.WriteString(block + "\n")
if err != nil {
return err
}
err = writer.Flush()
if err != nil {
return err
}
}
if err := scanner.Err(); err != nil {
return err
}
return nil
}
func main() {
if len(os.Args) != 4 {
fmt.Println("Please provide the source file path, the phrase to search for, and the destination file path. Example: script.exe input.txt \"my phrase\" output.txt")
return
}
filePath := os.Args[1]
phrase := os.Args[2]
newFilePath := os.Args[3]
err := findPhraseInFile(filePath, phrase, newFilePath)
if err != nil {
fmt.Printf("An error occurred: %v", err)
}
}