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

@FedericoPonzi FedericoPonzi commented Apr 19, 2016

Thanks!

@fboukezzoula

This comment has been minimized.

Copy link

@fboukezzoula fboukezzoula commented Jul 27, 2017

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

@hexiay

This comment has been minimized.

Copy link

@hexiay hexiay commented Oct 12, 2017

👍

@DineshGuptaa

This comment has been minimized.

Copy link

@DineshGuptaa DineshGuptaa commented Jun 8, 2018

Cool, Very helpful 👍

@malisetti

This comment has been minimized.

Copy link

@malisetti malisetti commented Jul 11, 2018

what is the 0 doing in the mode ?

@andrew-ledawson

This comment has been minimized.

Copy link

@andrew-ledawson andrew-ledawson 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

@mkozjak mkozjak commented Jan 25, 2019

Thanks!!

@RebelIT

This comment has been minimized.

Copy link

@RebelIT RebelIT commented Feb 14, 2020

TY for this!

@ookangzheng

This comment has been minimized.

Copy link

@ookangzheng ookangzheng commented Jul 14, 2020

Thanks ~~ 👍

@MarvWasTaken

This comment has been minimized.

Copy link

@MarvWasTaken MarvWasTaken commented Oct 28, 2020

Thank you! 👍

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.