Skip to content

Instantly share code, notes, and snippets.

@pascal08
Created January 4, 2019 16:56
Show Gist options
  • Save pascal08/022e75ddce89d7ec16315eb255e5b82d to your computer and use it in GitHub Desktop.
Save pascal08/022e75ddce89d7ec16315eb255e5b82d to your computer and use it in GitHub Desktop.
Find/Replace in multiple files
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