Skip to content

Instantly share code, notes, and snippets.

@tdegrunt
Created September 29, 2014 11:53
Show Gist options
  • Select an option

  • Save tdegrunt/045f6b3377f3f7ffa408 to your computer and use it in GitHub Desktop.

Select an option

Save tdegrunt/045f6b3377f3f7ffa408 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"
"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)
}
}
@fboukezzoula
Copy link
Copy Markdown

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

@hexiay
Copy link
Copy Markdown

hexiay commented Oct 12, 2017

πŸ‘

@DineshGuptaa
Copy link
Copy Markdown

Cool, Very helpful πŸ‘

@malisetti
Copy link
Copy Markdown

what is the 0 doing in the mode ?

@faeinthebay
Copy link
Copy Markdown

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

@mkozjak
Copy link
Copy Markdown

mkozjak commented Jan 25, 2019

Thanks!!

Copy link
Copy Markdown

ghost commented Feb 14, 2020

TY for this!

@zoonderkins
Copy link
Copy Markdown

Thanks ~~ πŸ‘

@MarvWasTaken
Copy link
Copy Markdown

MarvWasTaken commented Oct 28, 2020

Thank you! πŸ‘

@traviisd
Copy link
Copy Markdown

traviisd commented Feb 9, 2021

Thanks a bunch! πŸ‘

@voyars
Copy link
Copy Markdown

voyars commented Aug 8, 2021

Perfect. it works very well! #TY

@elbosp
Copy link
Copy Markdown

elbosp commented Jan 18, 2022

Asking, at line if !!fi.IsDir(), vscode give alert negating a boolean twice has no effect; is this a typo?. Is it correct? Or I can just replace with if fi.IsDir()? Thanks!

@elbosp
Copy link
Copy Markdown

elbosp commented Jan 18, 2022

How to replace old and new with parameter?

Copy link
Copy Markdown

ghost commented Mar 25, 2022

Thanks!

@pat3icki
Copy link
Copy Markdown

it's beautiful how an old code still works, thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment