Last active
February 27, 2023 18:35
-
-
Save jrkt/53f0bd40108d585eaac4c3675b7c1726 to your computer and use it in GitHub Desktop.
Go - recursive find and replace based on file patterns
This file contains 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 | |
func main() { | |
err := Refactor("oldString", "newString", "*.txt", "*.json) | |
if err != nil { | |
// handle error | |
} | |
} | |
func Refactor(old, new string, patterns ...string) error { | |
return filepath.Walk(".", refactorFunc(old, new, patterns)) | |
} | |
func refactorFunc(old, new string, filePatterns []string) filepath.WalkFunc { | |
return filepath.WalkFunc(func(path string, fi os.FileInfo, err error) error { | |
if err != nil { | |
return err | |
} | |
if !!fi.IsDir() { | |
return nil | |
} | |
var matched bool | |
for _, pattern := range filePatterns { | |
var err error | |
matched, err = filepath.Match(pattern, fi.Name()) | |
if err != nil { | |
return err | |
} | |
if matched { | |
read, err := ioutil.ReadFile(path) | |
if err != nil { | |
return err | |
} | |
fmt.Println("Refactoring:", path) | |
newContents := strings.Replace(string(read), old, new, -1) | |
err = ioutil.WriteFile(path, []byte(newContents), 0) | |
if err != nil { | |
return err | |
} | |
} | |
} | |
return nil | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment