-
Notifications
You must be signed in to change notification settings - Fork 1
/
sed.go
88 lines (85 loc) · 1.68 KB
/
sed.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
package main
import (
"fmt"
"regexp"
"strings"
)
func sed(s, pattern, replace string, insensitive, global bool) (result string, err error) {
if insensitive {
pattern = "(?i)" + pattern
}
re, err := regexp.Compile(pattern)
if err != nil {
return
}
if global {
for _, m := range re.FindAllStringSubmatch(s, -1) {
if m == nil {
return
}
s = strings.Replace(s, m[0], replace, 1)
result = s
for i := 0; i < len(m); i++ {
result = strings.Replace(result, "\\"+string(byte(48+i)), m[i], -1)
}
}
} else {
m := re.FindStringSubmatch(s)
if m == nil {
return
}
result = strings.Replace(s, m[0], replace, 1)
for i := 0; i < len(m); i++ {
result = strings.Replace(result, "\\"+string(byte(48+i)), m[i], -1)
}
}
return
}
func seddy(input, s string) (result string, err error) {
if !strings.HasPrefix(s, "s/") {
err = fmt.Errorf("not sed")
return
}
str := []rune(s[2:])
cmd := [][]rune{[]rune{}}
for i := 0; i < len(str); i++ {
if str[i] == '/' {
if i == 0 || str[i-1] != '\\' {
cmd = append(cmd, []rune{})
continue
}
}
cmd[len(cmd)-1] = append(cmd[len(cmd)-1], str[i])
}
if len(cmd) < 2 || len(cmd) > 3 {
err = fmt.Errorf("not sed")
return
}
pat := string(cmd[0])
rep := string(cmd[1])
ins := false
glo := false
if len(cmd) == 3 {
for _, flag := range cmd[2] {
switch flag {
case 'i':
if ins {
err = fmt.Errorf("invalid flag argument")
return
}
ins = true
case 'g':
if glo {
err = fmt.Errorf("invalid flag argument")
return
}
glo = true
default:
err = fmt.Errorf("invalid flag argument")
return
}
}
}
result, err = sed(input, pat, rep, ins, glo)
return
}