I am porting some ruby code to golang. I'm having difficulty finding a good equivalent for the below line and wondered if someone knew of a better solution than what I have below. The basic premise is find a line in a file that has a lot of spaces and remove the line.
I also thought of just using exec to call sed -i but when I tried that it didn't work, and the below did finally work.
Ruby:
File.write(filename, File.read(filename).gsub(/^\s*$/,""))
Golang:
b, err := ioutil.ReadFile(filename)
if err != nil {
return
}
// I happen to know that there will be at least 30 spaces,
// but I would really prefer to not use a hardcoded value here.
// I was just never able to make using '^\s*$' work in the regex.
r := regexp.MustCompile(`[ ]{30,}`) // there's a space in the []
newb := r.ReplaceAll(b, []byte(""))
err = ioutil.WriteFile(filename, newb, 0666)
if err != nil {
fmt.Printf("Unable to write to file (%+v)\n", err)
return
}
Turn on multiline mode, and your original pattern will work:
r := regexp.MustCompile(`(?m)^\s*$`)
Demo using strings: https://play.golang.org/p/6TsfgB83WgX
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With