Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Replace some text in a bunch of files with golang
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)
}
}
@FedericoPonzi

This comment has been minimized.

Copy link

commented Apr 19, 2016

Thanks!

@fboukezzoula

This comment has been minimized.

Copy link

commented Jul 27, 2017

Thanks too ;o) is working like a charm ....

@hexiay

This comment has been minimized.

Copy link

commented Oct 12, 2017

👍

@DineshGuptaa

This comment has been minimized.

Copy link

commented Jun 8, 2018

Cool, Very helpful 👍

@mseshachalam

This comment has been minimized.

Copy link

commented Jul 11, 2018

what is the 0 doing in the mode ?

@andrew-ledawson

This comment has been minimized.

Copy link

commented Aug 24, 2018

I think the fileMode being 0 is just setting the permission bits, see https://stackoverflow.com/questions/28969455/golang-properly-instantiate-os-filemode

@mkozjak

This comment has been minimized.

Copy link

commented Jan 25, 2019

Thanks!!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.