1+ package main
2+
3+ import (
4+ "fmt"
5+ "io/ioutil"
6+ "os"
7+ "strings"
8+ "regexp"
9+ flags "github.com/jessevdk/go-flags"
10+ )
11+
12+ const (
13+ Author = "webdevops.io"
14+ Version = "1.0"
15+ )
16+
17+ var opts struct {
18+ Search string `short:"s" long:"regex" description:"Search regexp" value-name:"RE"`
19+ Replace string `short:"r" long:"replace" description:"replace found substrings with RE" value-name:"RE"`
20+ IgnoreCase bool `short:"i" long:"ignore-case" description:"ignore pattern case"`
21+ PlainText bool `short:"p" long:"plain" description:"treat pattern as plain text"`
22+ Verbose bool `short:"v" long:"verbose" description:"verbose mode"`
23+ ShowVersion bool `short:"V" long:"version" description:"show version and exit"`
24+ ShowHelp bool `short:"h" long:"help" description:"show this help message"`
25+ }
26+
27+ var argparser = flags .NewParser (& opts , flags .PrintErrors | flags .PassDoubleDash )
28+
29+ func replaceInFile (file string ) {
30+ var err error
31+
32+ read , err := ioutil .ReadFile (file )
33+ if err != nil {
34+ panic (err )
35+ }
36+
37+ content := string (read )
38+
39+ if opts .PlainText {
40+ if strings .Contains (content , opts .Search ) {
41+ content = strings .Replace (content , opts .Search , opts .Replace , - 1 )
42+ writeContentToFile (file , content )
43+ }
44+ } else {
45+ regex := opts .Search
46+
47+ if opts .IgnoreCase {
48+ regex = "(?i:" + regex + ")"
49+ }
50+
51+ re := regexp .MustCompile (regex )
52+
53+ if re .MatchString (content ) {
54+ content = re .ReplaceAllString (content , opts .Replace )
55+ writeContentToFile (file , content )
56+ }
57+ }
58+
59+ }
60+
61+ func writeContentToFile (file string , content string ) {
62+ var err error
63+ err = ioutil .WriteFile (file , []byte (content ), 0 )
64+ if err != nil {
65+ panic (err )
66+ }
67+ }
68+
69+ func main () {
70+ args , err := argparser .Parse ()
71+ if err != nil {
72+ panic (err )
73+ os .Exit (1 )
74+ }
75+
76+ if opts .ShowVersion {
77+ fmt .Printf ("goreplace %s\n " , Version )
78+ return
79+ }
80+
81+ if (opts .ShowHelp ) || (opts .Search == "" ) || (opts .Replace == "" ) || (len (args ) > 0 ) {
82+ fmt .Println ("Usage: golang -s <search regex> -r <replace string> file1 file2 file3" )
83+ argparser .WriteHelp (os .Stdout )
84+ os .Exit (1 )
85+ }
86+
87+ for i := range args {
88+ var file string
89+ file = args [i ]
90+
91+ if opts .Verbose {
92+ fmt .Printf (" - checking %s\n " , file )
93+ }
94+ replaceInFile (file )
95+ }
96+
97+ os .Exit (0 )
98+ }
0 commit comments