-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
56 lines (48 loc) · 1.23 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
package main
import (
"bufio"
"fmt"
"os"
"regexp"
"strings"
"unicode/utf8"
"github.com/jessevdk/go-flags"
)
var defaultTarget = `[ \t]+`
var defaultReplaceWith = " "
func main() {
// parse options
var opts struct {
Target string `short:"t" long:"target" description:"replace target RegExp (default: '[ \t]+')"`
ReplaceWith string `short:"w" long:"with" description:"replace with this string (default: ' ')"`
}
_, err := flags.Parse(&opts)
if err != nil {
panic(err)
}
target := defaultTarget
if opts.Target != "" {
target = opts.Target
}
replaceWith := defaultReplaceWith
if opts.ReplaceWith != "" {
replaceWith = opts.ReplaceWith
}
// replace stdin, output to stdout
scanner := bufio.NewScanner(os.Stdin)
for scanner.Scan() {
inputText := scanner.Text()
result := ReplaceHead(inputText, target, replaceWith)
fmt.Println(result)
}
if err := scanner.Err(); err != nil {
fmt.Fprintln(os.Stderr, "reading standard input:", err)
}
}
func ReplaceHead(text string, target string, replaceWith string) string {
re := regexp.MustCompile("^" + target)
return re.ReplaceAllStringFunc(text, func(s string) string {
spaceCount := utf8.RuneCountInString(s)
return strings.Repeat(replaceWith, spaceCount)
})
}