Globally replace text in several files: Difference between revisions
Globally replace text in several files (view source)
Revision as of 17:25, 28 October 2011
, 12 years agoGo solution
m (→{{header|C++}}: cpp tag (C++ does not work)) |
(Go solution) |
||
Line 171:
foreach (fn; "a.txt b.txt c.txt".split()) {
write(fn, replace(cast(string)read(fn), from, to));
}
}</lang>
=={{header|Go}}==
<lang go>package main
import (
"bytes"
"fmt"
"io/ioutil"
"os"
)
func main() {
gRepNFiles("Goodbye London!", "Hello New York!", []string{
"a.txt",
"b.txt",
"c.txt",
})
}
func gRepNFiles(olds, news string, files []string) {
oldb := []byte(olds)
newb := []byte(news)
for _, fn := range files {
gRepFile(oldb, newb, fn)
}
}
func gRepFile(oldb, newb []byte, fn string) {
fi, err := os.Stat(fn)
if err != nil {
fmt.Println(err)
return
}
b, err := ioutil.ReadFile(fn)
if err != nil {
fmt.Println(err)
return
}
r := bytes.Replace(b, oldb, newb, -1)
err = ioutil.WriteFile(fn, r, fi.Permission())
if err != nil {
fmt.Println(err)
}
}</lang>
|