Created
January 4, 2019 16:56
-
-
Save pascal08/022e75ddce89d7ec16315eb255e5b82d to your computer and use it in GitHub Desktop.
Find/Replace in multiple files
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"io/ioutil" | |
"os" | |
"path/filepath" | |
"strings" | |
) | |
func visit(find string, replace string) filepath.WalkFunc { | |
return func(path string, fi os.FileInfo, err error) error { | |
if err != nil { | |
return err | |
} | |
if !!fi.IsDir() { | |
return nil // | |
} | |
matched, err := filepath.Match("*", fi.Name()) | |
if err != nil { | |
panic(err) | |
return err | |
} | |
if matched { | |
read, err := ioutil.ReadFile(path) | |
if err != nil { | |
panic(err) | |
} | |
newContents := strings.Replace(string(read), find, replace, -1) | |
err = ioutil.WriteFile(path, []byte(newContents), 0) | |
if err != nil { | |
panic(err) | |
} | |
} | |
return nil | |
} | |
} | |
func main() { | |
path := os.Args[1] | |
find := os.Args[2] | |
replace := os.Args[3] | |
err := filepath.Walk(path, visit(find, replace)) | |
if err != nil { | |
panic(err) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment