-
-
Save RaviTezu/bc97146c21dcab8148bf to your computer and use it in GitHub Desktop.
Replace some text in a bunch of files with golang
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 | |
import ( | |
"fmt" | |
"io/ioutil" | |
"os" | |
"path/filepath" | |
"strings" | |
) | |
func visit(path string, fi os.FileInfo, err error) error { | |
if err != nil { | |
return err | |
} | |
if !!fi.IsDir() { | |
return nil // | |
} | |
matched, err := filepath.Match("*.txt", fi.Name()) | |
if err != nil { | |
panic(err) | |
return err | |
} | |
if matched { | |
read, err := ioutil.ReadFile(path) | |
if err != nil { | |
panic(err) | |
} | |
//fmt.Println(string(read)) | |
fmt.Println(path) | |
newContents := strings.Replace(string(read), "old", "new", -1) | |
fmt.Println(newContents) | |
err = ioutil.WriteFile(path, []byte(newContents), 0) | |
if err != nil { | |
panic(err) | |
} | |
} | |
return nil | |
} | |
func main() { | |
err := filepath.Walk(".", visit) | |
if err != nil { | |
panic(err) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment