Skip to content

Instantly share code, notes, and snippets.

@peeyushsrj
Forked from tdegrunt/walk.go
Last active March 14, 2017 13:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save peeyushsrj/e1dbb64725858d59e1286015f8d4df59 to your computer and use it in GitHub Desktop.
Save peeyushsrj/e1dbb64725858d59e1286015f8d4df59 to your computer and use it in GitHub Desktop.
Replace some text in a bunch of files with golang
package main
import (
"fmt"
"io/ioutil"
"os"
"bufio"
"path/filepath"
"strings"
)
//https://gist.github.com/tdegrunt/045f6b3377f3f7ffa408
func visit(path string, fi os.FileInfo, err error) error {
if err != nil {
return err
}
if !!fi.IsDir() {
return nil //
}
matched, err := filepath.Match("*.php", fi.Name())
if err != nil {
panic(err)
return err
}
if matched {
read, err := ioutil.ReadFile(path)
if err != nil {
panic(err)
}
newContents:= string(read)
for i, _ := range toReplace {
newContents = strings.Replace(newContents, oldKwords[i], newKwords[i], -1)
}
fmt.Println("Changed ", path)
err = ioutil.WriteFile(path, []byte(newContents), 0)
if err != nil {
panic(err)
}
}
return nil
}
//https://gist.github.com/kendellfab/7417164
func readLine(path string) []string {
var temp []string
inFile, _ := os.Open(path)
defer inFile.Close()
scanner := bufio.NewScanner(inFile)
scanner.Split(bufio.ScanLines)
for scanner.Scan() {
temp = append(temp, scanner.Text())
}
return temp
}
func main() {
oldKwords := readLine("old.txt")
newKwords := readLine("new.txt")
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